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
1207B
1207
B
ru
B. Заполнение квадратов
<div class="problem-statement"><div class="header"><div class="title">B. Заполнение квадратов</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам заданы две матрицы $$$A$$$ и $$$B$$$. В каждой матрице ровно $$$n$$$ строк и $$$m$$$ столбцов. Каждый элемент $$$A$$$ — $$$0$$$ или $$$1$$$; каждый элемент $$$B$$$ изначально равен $$$0$$$.</p><p>Вы можете провести любое количество операций с матрицей $$$B$$$. Для проведения операции вы должны выбрать любую подматрицу $$$B$$$ размера $$$2 \times 2$$$ и заменить все элементы в этой подматрице на $$$1$$$. Иными словами, вы выбираете два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x &lt; n$$$, $$$1 \le y &lt; m$$$), а затем заменяете все элементы $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ и $$$B_{x + 1, y + 1}$$$ на $$$1$$$.</p><p>Ваша задача — сделать матрицу $$$B$$$ равной матрице $$$A$$$. Две матрицы $$$A$$$ и $$$B$$$ равны тогда и только тогда, когда каждый элемент матрицы $$$A$$$ равен соответствующему элементу матрицы $$$B$$$.</p><p>Можно ли сделать матрицы равными? Если это так, вы должны найти последовательность операций, которые делают матрицу $$$B$$$ равной матрице $$$A$$$. Обратите внимание, что минимизировать количество операций не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 50$$$).</p><p>Затем следуют $$$n$$$ строк, в каждой по $$$m$$$ целых чисел. $$$j$$$-е число в $$$i$$$-й строке — $$$A_{i, j}$$$. Каждое число равно либо $$$0$$$, либо $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно сделать $$$B$$$ равной $$$A$$$, выведите одно число $$$-1$$$.</p><p>Иначе выведите любую последовательность операций, превращающую $$$B$$$ в $$$A$$$, в следующем формате: в первой строке выведите одно целое число $$$k$$$ — количество операций, а затем выведите $$$k$$$ строк, в каждой из которых должны быть два целых числа $$$x$$$ и $$$y$$$ для соответствующей операции (заменить все элементы $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ и $$$B_{x + 1, y + 1}$$$ на $$$1$$$). Должно выполняться условие $$$0 \le k \le 2500$$$.</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 1 1 1 1 1 0 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 1 1 2 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 0 1 1 0 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 0 0 0 0 </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> $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$ </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="5c2130828f8ed7be9be8450394b9e80f"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='5c2130828f8ed7be9be8450394b9e80f'>&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%2F1207%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='5c2130828f8ed7be9be8450394b9e80f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='5c2130828f8ed7be9be8450394b9e80f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='5c2130828f8ed7be9be8450394b9e80f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393972"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5c2130828f8ed7be9be8450394b9e80f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393972"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1506ab1e6b02b271289749798fdfd1a4037b3106"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ и $$$B$$$. В каждой матрице ровно $$$n$$$ строк и $$$m$$$ столбцов. Каждый элемент $$$A$$$ — $$$0$$$ или $$$1$$$; каждый элемент $$$B$$$ изначально равен $$$0$$$.</p><p>Вы можете провести любое количество операций с матрицей $$$B$$$. Для проведения операции вы должны выбрать любую подматрицу $$$B$$$ размера $$$2 \times 2$$$ и заменить все элементы в этой подматрице на $$$1$$$. Иными словами, вы выбираете два целых числа $$$x$$$ и $$$y$$$ ($$$1 \le x &lt; n$$$, $$$1 \le y &lt; m$$$), а затем заменяете все элементы $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ и $$$B_{x + 1, y + 1}$$$ на $$$1$$$.</p><p>Ваша задача — сделать матрицу $$$B$$$ равной матрице $$$A$$$. Две матрицы $$$A$$$ и $$$B$$$ равны тогда и только тогда, когда каждый элемент матрицы $$$A$$$ равен соответствующему элементу матрицы $$$B$$$.</p><p>Можно ли сделать матрицы равными? Если это так, вы должны найти последовательность операций, которые делают матрицу $$$B$$$ равной матрице $$$A$$$. Обратите внимание, что минимизировать количество операций не нужно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 50$$$).</p><p>Затем следуют $$$n$$$ строк, в каждой по $$$m$$$ целых чисел. $$$j$$$-е число в $$$i$$$-й строке — $$$A_{i, j}$$$. Каждое число равно либо $$$0$$$, либо $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно сделать $$$B$$$ равной $$$A$$$, выведите одно число $$$-1$$$.</p><p>Иначе выведите любую последовательность операций, превращающую $$$B$$$ в $$$A$$$, в следующем формате: в первой строке выведите одно целое число $$$k$$$ — количество операций, а затем выведите $$$k$$$ строк, в каждой из которых должны быть два целых числа $$$x$$$ и $$$y$$$ для соответствующей операции (заменить все элементы $$$B_{x, y}$$$, $$$B_{x, y + 1}$$$, $$$B_{x + 1, y}$$$ и $$$B_{x + 1, y + 1}$$$ на $$$1$$$). Должно выполняться условие $$$0 \le k \le 2500$$$.</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 1 1 1 1 1 0 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 1 1 2 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 0 1 1 0 1 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 2 0 0 0 0 0 0 </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> $$$\begin{matrix} 0 &amp; 0 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 0 &amp; &amp; 1 &amp; 1 &amp; 1 &amp; &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 0 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 &amp; \rightarrow &amp; 1 &amp; 1 &amp; 1 \\ 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 0 &amp; 0 &amp; &amp; 0 &amp; 1 &amp; 1 \end{matrix}$$$ </center></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812482e69ecf1628',t:'MTY5NjY2NDU4OC43NzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1200"]
1207C
1207
C
ru
C. Газопровод
<div class="problem-statement"><div class="header"><div class="title">C. Газопровод</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам назначили задачу проложить газопровод вдоль дороги. Для простоты будем считать, что дорога — это отрезок $$$[0, n]$$$ на оси $$$OX$$$. На дороге может быть несколько перекрестков, но для простоты будем считать каждый перекресток как интервал $$$(x, x + 1)$$$ для некоторого целого $$$x$$$. Таким образом, можно представить дорогу как двоичную строку, состоящую из $$$n$$$ символов, где цифра <span class="tex-font-style-tt">0</span> означает, что текущий интервал не содержит перекресток, а <span class="tex-font-style-tt">1</span> означает, что интервал содержит перекресток.</p><p>Обычно газопровод можно установить вдоль дороги на высоте $$$1$$$ вместе с поддерживающими его столбами в каждой целой точке (поэтому при установке вдоль дороги $$$[0, n]$$$ нам необходимо поставить $$$n + 1$$$ столб). Но на перекрестках нам необходимо поднять трубу на высоту $$$2$$$, чтобы она не мешала проезду машин.</p><p>Мы можем поднять или опустить трубу за счет вставки зигзагообразных частей. Каждый зигзаг можно представить как отрезок $$$[x, x + 1]$$$ с целым $$$x$$$, состоящий из трех частей: $$$0.5$$$ единицы горизонтальной трубы + $$$1$$$ единицы вертикальной трубы + $$$0.5$$$ горизонтальной. Заметьте, что если труба находится на высоте $$$2$$$, столбы, ее поддерживающие, также должны быть длины $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/bc708a588ae509e2e30035cc9984dcdc444f59b5.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Каждая единица длины газопровода стоит нам $$$a$$$ бурлей, а каждая единица длины столба — $$$b$$$ бурлей. Поэтому не всегда выгодно просто пустить трубопровод на высоте $$$2$$$. Определите форму трубопровода с минимальной возможной ценой, а также его цену.</p><p>Заметим, что вы <span class="tex-font-style-bf">обязаны</span> начать и закончить трубу на высоте $$$1$$$, а также гарантируется, что первый и последний символы во входной строке обязательно равны <span class="tex-font-style-tt">0</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно число $$$T$$$ ($$$1 \le T \le 100$$$) — количество независимых запросов. В следующих $$$2 \cdot T$$$ строках заданы запросы — один запрос на две строки.</p><p>В первой строке заданы три целых числа $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — длина дороги, цена за единицу длины трубы и цена за единицу длины столба, соответственно.</p><p>Во второй строке задана двоичная строка $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — описание дороги.</p><p>Гарантируется, что суммарная длина строк $$$s$$$ во всех запросах не превосходит $$$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 8 2 5 00110010 8 1 1 00110010 9 100000000 100000000 010101010 2 5 1 00 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 94 25 2900000000 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Оптимальный газопровод для первого запроса изображен на рисунке сверху.</p><p>Оптимальный газопровод для второго запроса изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/634260f16e521498bfd8af22c5055e870cb98115.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Оптимальный (и единственный) газопровод для третьего примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/04e0bf496c066193c2b240987fe9fb84abef14a5.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Оптимальный газопровод для четвертого примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a4c9cc04a2819f2c05b98c49bd0f4eab76cf40da.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="e4050d3a339d73f617e7ba5a100c3498"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='e4050d3a339d73f617e7ba5a100c3498'>&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%2F1207%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='e4050d3a339d73f617e7ba5a100c3498'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='e4050d3a339d73f617e7ba5a100c3498'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='e4050d3a339d73f617e7ba5a100c3498'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393973"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e4050d3a339d73f617e7ba5a100c3498'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393973"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_31a3863072910ee1ca776ec00a69471dd29cf526"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам назначили задачу проложить газопровод вдоль дороги. Для простоты будем считать, что дорога — это отрезок $$$[0, n]$$$ на оси $$$OX$$$. На дороге может быть несколько перекрестков, но для простоты будем считать каждый перекресток как интервал $$$(x, x + 1)$$$ для некоторого целого $$$x$$$. Таким образом, можно представить дорогу как двоичную строку, состоящую из $$$n$$$ символов, где цифра <span class="tex-font-style-tt">0</span> означает, что текущий интервал не содержит перекресток, а <span class="tex-font-style-tt">1</span> означает, что интервал содержит перекресток.</p><p>Обычно газопровод можно установить вдоль дороги на высоте $$$1$$$ вместе с поддерживающими его столбами в каждой целой точке (поэтому при установке вдоль дороги $$$[0, n]$$$ нам необходимо поставить $$$n + 1$$$ столб). Но на перекрестках нам необходимо поднять трубу на высоту $$$2$$$, чтобы она не мешала проезду машин.</p><p>Мы можем поднять или опустить трубу за счет вставки зигзагообразных частей. Каждый зигзаг можно представить как отрезок $$$[x, x + 1]$$$ с целым $$$x$$$, состоящий из трех частей: $$$0.5$$$ единицы горизонтальной трубы + $$$1$$$ единицы вертикальной трубы + $$$0.5$$$ горизонтальной. Заметьте, что если труба находится на высоте $$$2$$$, столбы, ее поддерживающие, также должны быть длины $$$2$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/bc708a588ae509e2e30035cc9984dcdc444f59b5.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Каждая единица длины газопровода стоит нам $$$a$$$ бурлей, а каждая единица длины столба — $$$b$$$ бурлей. Поэтому не всегда выгодно просто пустить трубопровод на высоте $$$2$$$. Определите форму трубопровода с минимальной возможной ценой, а также его цену.</p><p>Заметим, что вы <span class="tex-font-style-bf">обязаны</span> начать и закончить трубу на высоте $$$1$$$, а также гарантируется, что первый и последний символы во входной строке обязательно равны <span class="tex-font-style-tt">0</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано одно число $$$T$$$ ($$$1 \le T \le 100$$$) — количество независимых запросов. В следующих $$$2 \cdot T$$$ строках заданы запросы — один запрос на две строки.</p><p>В первой строке заданы три целых числа $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — длина дороги, цена за единицу длины трубы и цена за единицу длины столба, соответственно.</p><p>Во второй строке задана двоичная строка $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — описание дороги.</p><p>Гарантируется, что суммарная длина строк $$$s$$$ во всех запросах не превосходит $$$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 8 2 5 00110010 8 1 1 00110010 9 100000000 100000000 010101010 2 5 1 00 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 94 25 2900000000 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Оптимальный газопровод для первого запроса изображен на рисунке сверху.</p><p>Оптимальный газопровод для второго запроса изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/634260f16e521498bfd8af22c5055e870cb98115.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Оптимальный (и единственный) газопровод для третьего примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/04e0bf496c066193c2b240987fe9fb84abef14a5.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Оптимальный газопровод для четвертого примера изображен ниже:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a4c9cc04a2819f2c05b98c49bd0f4eab76cf40da.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 10:43: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:'812482f77e139d64',t:'MTY5NjY2NDU5MC40NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1207D
1207
D
ru
D. Количество перестановок
<div class="problem-statement"><div class="header"><div class="title">D. Количество перестановок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано $$$n$$$ пар чисел: $$$(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$$$. Последовательность считается плохой, если она отсортирована в порядке неубывания по первым элементам или если она отсортирована в порядке неубывания по вторым элементам. Иначе последовательность считается хорошей. Примеры хороших и плохих последовательностей:</p><ul> <li> $$$s = [(1, 2), (3, 2), (3, 1)]$$$ — плохая, потому что последовательность первых элементов отсортирована: $$$[1, 3, 3]$$$; </li><li> $$$s = [(1, 2), (3, 2), (1, 2)]$$$ — плохая, потому что последовательность вторых элементов отсортирована: $$$[2, 2, 2]$$$; </li><li> $$$s = [(1, 1), (2, 2), (3, 3)]$$$ — плохая, потому что обе последовательности (последовательность первых элементов и последовательность вторых элементов) отсортированы; </li><li> $$$s = [(1, 3), (3, 3), (2, 2)]$$$ — хорошая, потому что обе последовательности (последовательность первых $$$([1, 3, 2])$$$ и последовательность вторых элементов $$$([3, 3, 2])$$$) не отсортированы. </li></ul><p>Посчитайте количество перестановок длины $$$n$$$ таких, что после применения этой перестановки к последовательности $$$s$$$ она станет хорошей последовательностью. </p><p>Перестановка $$$p$$$ длины $$$n$$$ это последовательность $$$p_1, p_2, \dots , p_n$$$ состоящая из $$$n$$$ различных чисел от $$$1$$$ до $$$n$$$ ($$$1 \le p_i \le n$$$). Если вы примените перестановку $$$p_1, p_2, \dots , p_n$$$ к последовательности $$$s_1, s_2, \dots , s_n$$$ вы получите последовательность $$$s_{p_1}, s_{p_2}, \dots , s_{p_n}$$$. Например, если $$$s = [(1, 2), (1, 3), (2, 3)]$$$ и $$$p = [2, 3, 1]$$$, то $$$s$$$ превратится $$$[(1, 3), (2, 3), (1, 2)]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).</p><p>Следующие $$$n$$$ строк содержат описание последовательности $$$s$$$. $$$i$$$-я строка содержит числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — первый и второй элементы $$$i$$$-й пары последовательности.</p><p><span class="tex-font-style-bf">Последовательность $$$s$$$ может содержать одинаковые элементы</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество перестановок длины $$$n$$$ таких, что после применения этой перестановки к последовательности $$$s$$$ она станет хорошей последовательностью. Так как количество таких перестановок может быть велико, выведите ответ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 2 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 3 2 2 2 1 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере есть шесть перестановок длины $$$3$$$: </p><ol> <li> если $$$p = [1, 2, 3]$$$, то $$$s = [(1, 1), (2, 2), (3, 1)]$$$ — плохая последовательность (отсортирована по первым элементам); </li><li> если $$$p = [1, 3, 2]$$$, то $$$s = [(1, 1), (3, 1), (2, 2)]$$$ — плохая последовательность (отсортирована по вторым элементам); </li><li> если $$$p = [2, 1, 3]$$$, то $$$s = [(2, 2), (1, 1), (3, 1)]$$$ — хорошая последовательность; </li><li> если $$$p = [2, 3, 1]$$$, то $$$s = [(2, 2), (3, 1), (1, 1)]$$$ — хорошая последовательность; </li><li> если $$$p = [3, 1, 2]$$$, то $$$s = [(3, 1), (1, 1), (2, 2)]$$$ — плохая последовательность (отсортирована по вторым элементам); </li><li> если $$$p = [3, 2, 1]$$$, то $$$s = [(3, 1), (2, 2), (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="a5d4e3f745b0e2d8dd0b73105271c409"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='a5d4e3f745b0e2d8dd0b73105271c409'>&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%2F1207%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='a5d4e3f745b0e2d8dd0b73105271c409'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='a5d4e3f745b0e2d8dd0b73105271c409'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a5d4e3f745b0e2d8dd0b73105271c409'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393974"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a5d4e3f745b0e2d8dd0b73105271c409'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393974"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_18b00f12a8d890e03f0f3f8d0a4a09efe524aa10"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ пар чисел: $$$(a_1, b_1), (a_2, b_2), \dots , (a_n, b_n)$$$. Последовательность считается плохой, если она отсортирована в порядке неубывания по первым элементам или если она отсортирована в порядке неубывания по вторым элементам. Иначе последовательность считается хорошей. Примеры хороших и плохих последовательностей:</p><ul> <li> $$$s = [(1, 2), (3, 2), (3, 1)]$$$ — плохая, потому что последовательность первых элементов отсортирована: $$$[1, 3, 3]$$$; </li><li> $$$s = [(1, 2), (3, 2), (1, 2)]$$$ — плохая, потому что последовательность вторых элементов отсортирована: $$$[2, 2, 2]$$$; </li><li> $$$s = [(1, 1), (2, 2), (3, 3)]$$$ — плохая, потому что обе последовательности (последовательность первых элементов и последовательность вторых элементов) отсортированы; </li><li> $$$s = [(1, 3), (3, 3), (2, 2)]$$$ — хорошая, потому что обе последовательности (последовательность первых $$$([1, 3, 2])$$$ и последовательность вторых элементов $$$([3, 3, 2])$$$) не отсортированы. </li></ul><p>Посчитайте количество перестановок длины $$$n$$$ таких, что после применения этой перестановки к последовательности $$$s$$$ она станет хорошей последовательностью. </p><p>Перестановка $$$p$$$ длины $$$n$$$ это последовательность $$$p_1, p_2, \dots , p_n$$$ состоящая из $$$n$$$ различных чисел от $$$1$$$ до $$$n$$$ ($$$1 \le p_i \le n$$$). Если вы примените перестановку $$$p_1, p_2, \dots , p_n$$$ к последовательности $$$s_1, s_2, \dots , s_n$$$ вы получите последовательность $$$s_{p_1}, s_{p_2}, \dots , s_{p_n}$$$. Например, если $$$s = [(1, 2), (1, 3), (2, 3)]$$$ и $$$p = [2, 3, 1]$$$, то $$$s$$$ превратится $$$[(1, 3), (2, 3), (1, 2)]$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$).</p><p>Следующие $$$n$$$ строк содержат описание последовательности $$$s$$$. $$$i$$$-я строка содержит числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$) — первый и второй элементы $$$i$$$-й пары последовательности.</p><p><span class="tex-font-style-bf">Последовательность $$$s$$$ может содержать одинаковые элементы</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите количество перестановок длины $$$n$$$ таких, что после применения этой перестановки к последовательности $$$s$$$ она станет хорошей последовательностью. Так как количество таких перестановок может быть велико, выведите ответ по модулю $$$998244353$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 2 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 3 2 2 2 1 2 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 1 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере есть шесть перестановок длины $$$3$$$: </p><ol> <li> если $$$p = [1, 2, 3]$$$, то $$$s = [(1, 1), (2, 2), (3, 1)]$$$ — плохая последовательность (отсортирована по первым элементам); </li><li> если $$$p = [1, 3, 2]$$$, то $$$s = [(1, 1), (3, 1), (2, 2)]$$$ — плохая последовательность (отсортирована по вторым элементам); </li><li> если $$$p = [2, 1, 3]$$$, то $$$s = [(2, 2), (1, 1), (3, 1)]$$$ — хорошая последовательность; </li><li> если $$$p = [2, 3, 1]$$$, то $$$s = [(2, 2), (3, 1), (1, 1)]$$$ — хорошая последовательность; </li><li> если $$$p = [3, 1, 2]$$$, то $$$s = [(3, 1), (1, 1), (2, 2)]$$$ — плохая последовательность (отсортирована по вторым элементам); </li><li> если $$$p = [3, 2, 1]$$$, то $$$s = [(3, 1), (2, 2), (1, 1)]$$$ — хорошая последовательность. </li></ol></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483021b1c03dd',t:'MTY5NjY2NDU5Mi4zOTAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "*1800"]
1207E
1207
E
ru
E. XOR-угадайка
<div class="problem-statement"><div class="header"><div class="title">E. XOR-угадайка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача. Не забывайте о том, что ваша программа должна каждый раз после вывода запроса сбрасывать буфер вывода.</span> Для сброса буфера вывода можно использовать <span class="tex-font-style-tt">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>Мы загадали целое число $$$x$$$, не меньше $$$0$$$ и не больше $$$2^{14} - 1$$$. Вы должны угадать это число.</p><p>Для этого вы можете задать не более $$$2$$$ запросов. Каждый запрос должен состоять из $$$100$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{100}$$$ (каждое число должно быть не меньше $$$0$$$ и не больше $$$2^{14} - 1$$$). В ответ на запрос мы выберем целое число $$$i$$$ ($$$1 \le i \le 100$$$) и сообщим вам значение $$$a_i \oplus x$$$ (побитовое исключающее ИЛИ чисел $$$a_i$$$ и $$$x$$$). Все $$$200$$$ чисел, которые вы используете в запросах, обязательно должны быть различны.</p><p><span class="tex-font-style-bf">Гарантируется, что значение $$$x$$$ в каждом тесте зафиксировано, но выбор числа $$$i$$$ в каждом запросе может зависеть от того, какие числа вы посылаете.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Чтобы дать ответ на задачу, ваша программа должна отправить одну строку $$$!$$$ $$$x$$$ <span class="tex-font-style-it">с переводом строки в конце</span>. После этого программа должна сбросить буфер вывода и завершиться.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>До того, как ваша программа даст ответ, она может отправить не более $$$2$$$ запросов. Чтобы отправить запрос, выведите строку следующего формата: $$$?$$$ $$$a_1$$$ $$$a_2$$$ ... $$$a_{100}$$$, где каждое $$$a_j$$$ должно быть целым числом из отрезка $$$[0, 2^{14} - 1]$$$. <span class="tex-font-style-it">Строка, которую вы отправляете, должна заканчиваться символов перевода строки</span>. После отправки запроса программа должна сбросить буфер вывода и прочитать ответ на запрос — значение $$$a_i \oplus x$$$ для некоторого $$$i \in [1, 100]$$$. <span class="tex-font-style-bf">Никакое число не должно быть использовано в запросах дважды, ни в пределах одного и того же запроса, ни в разных запросах</span>.</p><p>Если вы зададите некорректный запрос (или же количество запросов превысит $$$2$$$), ответом будет число $$$-1$$$. Если ваша программа получила такой ответ, она должна немедленно завершиться — иначе вы можете получить вердикт «Ошибка исполнения», «Превышено ограничение времени» или какой-нибудь другой, а не «Неправильный ответ».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 0 32</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 3 5 6 ? 32 24 37 ! 5</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пример взаимодействия <span class="tex-font-style-bf">не является корректным</span> — вы должны отправить <span class="tex-font-style-bf">ровно</span> $$$100$$$ целых чисел в каждом запросе. Все остальное корректно.</p><p><span class="tex-font-style-bf">Взломы в этой задаче запрещены</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="172455ca77600065d42f1b0cb97532cb"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='172455ca77600065d42f1b0cb97532cb'>&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%2F1207%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='172455ca77600065d42f1b0cb97532cb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='172455ca77600065d42f1b0cb97532cb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='172455ca77600065d42f1b0cb97532cb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393975"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='172455ca77600065d42f1b0cb97532cb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393975"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7ea4c5e15948b76d758894ceb25c951ee53cb81e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. XOR-угадайка</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Это интерактивная задача. Не забывайте о том, что ваша программа должна каждый раз после вывода запроса сбрасывать буфер вывода.</span> Для сброса буфера вывода можно использовать <span class="tex-font-style-tt">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>Мы загадали целое число $$$x$$$, не меньше $$$0$$$ и не больше $$$2^{14} - 1$$$. Вы должны угадать это число.</p><p>Для этого вы можете задать не более $$$2$$$ запросов. Каждый запрос должен состоять из $$$100$$$ целых чисел $$$a_1$$$, $$$a_2$$$, ..., $$$a_{100}$$$ (каждое число должно быть не меньше $$$0$$$ и не больше $$$2^{14} - 1$$$). В ответ на запрос мы выберем целое число $$$i$$$ ($$$1 \le i \le 100$$$) и сообщим вам значение $$$a_i \oplus x$$$ (побитовое исключающее ИЛИ чисел $$$a_i$$$ и $$$x$$$). Все $$$200$$$ чисел, которые вы используете в запросах, обязательно должны быть различны.</p><p><span class="tex-font-style-bf">Гарантируется, что значение $$$x$$$ в каждом тесте зафиксировано, но выбор числа $$$i$$$ в каждом запросе может зависеть от того, какие числа вы посылаете.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Чтобы дать ответ на задачу, ваша программа должна отправить одну строку $$$!$$$ $$$x$$$ <span class="tex-font-style-it">с переводом строки в конце</span>. После этого программа должна сбросить буфер вывода и завершиться.</p></div><div><div class="section-title">Протокол взаимодействия</div><p>До того, как ваша программа даст ответ, она может отправить не более $$$2$$$ запросов. Чтобы отправить запрос, выведите строку следующего формата: $$$?$$$ $$$a_1$$$ $$$a_2$$$ ... $$$a_{100}$$$, где каждое $$$a_j$$$ должно быть целым числом из отрезка $$$[0, 2^{14} - 1]$$$. <span class="tex-font-style-it">Строка, которую вы отправляете, должна заканчиваться символов перевода строки</span>. После отправки запроса программа должна сбросить буфер вывода и прочитать ответ на запрос — значение $$$a_i \oplus x$$$ для некоторого $$$i \in [1, 100]$$$. <span class="tex-font-style-bf">Никакое число не должно быть использовано в запросах дважды, ни в пределах одного и того же запроса, ни в разных запросах</span>.</p><p>Если вы зададите некорректный запрос (или же количество запросов превысит $$$2$$$), ответом будет число $$$-1$$$. Если ваша программа получила такой ответ, она должна немедленно завершиться — иначе вы можете получить вердикт «Ошибка исполнения», «Превышено ограничение времени» или какой-нибудь другой, а не «Неправильный ответ».</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 0 32</pre></div><div class="output"><div class="title">Выходные данные</div><pre> ? 3 5 6 ? 32 24 37 ! 5</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Пример взаимодействия <span class="tex-font-style-bf">не является корректным</span> — вы должны отправить <span class="tex-font-style-bf">ровно</span> $$$100$$$ целых чисел в каждом запросе. Все остальное корректно.</p><p><span class="tex-font-style-bf">Взломы в этой задаче запрещены</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 10:43:13</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:'8124830e09817b53',t:'MTY5NjY2NDU5My45MzAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0418\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432\u043d\u0430\u044f \u0437\u0430\u0434\u0430\u0447\u0430", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0438\u043d\u0442\u0435\u0440\u0430\u043a\u0442\u0438\u0432", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1900"]
1207F
1207
F
ru
F. Задача об остатках
<div class="problem-statement"><div class="header"><div class="title">F. Задача об остатках</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>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$$$, состоящий из $$$500000$$$ целых чисел (элементы нумеруются от $$$1$$$ до $$$500000$$$). Изначально все элементы $$$a$$$ — нули.</p><p>К этому массиву поступают запросы двух типов:</p><ul> <li> $$$1$$$ $$$x$$$ $$$y$$$ — увеличить $$$a_x$$$ на $$$y$$$; </li><li> $$$2$$$ $$$x$$$ $$$y$$$ — посчитать $$$\sum\limits_{i \in R(x, y)} a_i$$$, где $$$R(x, y)$$$ — множество всех целых чисел от $$$1$$$ до $$$500000$$$, дающих остаток $$$y$$$ при делении на $$$x$$$. </li></ul><p>Можете ли вы обработать все запросы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$q$$$ ($$$1 \le q \le 500000$$$) — количество запросов.</p><p>Затем следуют $$$q$$$ строк, каждая из которых задает запрос. В $$$i$$$-й строке записаны три целых числа $$$t_i$$$, $$$x_i$$$ и $$$y_i$$$ ($$$1 \le t_i \le 2$$$). Если $$$t_i = 1$$$, то это запрос первого типа, $$$1 \le x_i \le 500000$$$, и $$$-1000 \le y_i \le 1000$$$. Если $$$t_i = 2$$$, то это запрос второго типа, $$$1 \le x_i \le 500000$$$, и $$$0 \le y_i &lt; x_i$$$.</p><p>Гарантируется, что во входных данных есть хотя бы один запрос типа $$$2$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса типа $$$2$$$ выведите одно целое число — ответ на этот запрос.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 4 2 3 0 2 4 3 1 4 -4 2 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 4 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="f11d8b6ae753cb66b559ca33ed1c1d64"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='f11d8b6ae753cb66b559ca33ed1c1d64'>&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%2F1207%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='f11d8b6ae753cb66b559ca33ed1c1d64'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='f11d8b6ae753cb66b559ca33ed1c1d64'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='f11d8b6ae753cb66b559ca33ed1c1d64'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393976"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f11d8b6ae753cb66b559ca33ed1c1d64'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393976"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b6115f5c4df7b81e81543b552c67ad0c9765b78f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У вас есть массив $$$a$$$, состоящий из $$$500000$$$ целых чисел (элементы нумеруются от $$$1$$$ до $$$500000$$$). Изначально все элементы $$$a$$$ — нули.</p><p>К этому массиву поступают запросы двух типов:</p><ul> <li> $$$1$$$ $$$x$$$ $$$y$$$ — увеличить $$$a_x$$$ на $$$y$$$; </li><li> $$$2$$$ $$$x$$$ $$$y$$$ — посчитать $$$\sum\limits_{i \in R(x, y)} a_i$$$, где $$$R(x, y)$$$ — множество всех целых чисел от $$$1$$$ до $$$500000$$$, дающих остаток $$$y$$$ при делении на $$$x$$$. </li></ul><p>Можете ли вы обработать все запросы?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$q$$$ ($$$1 \le q \le 500000$$$) — количество запросов.</p><p>Затем следуют $$$q$$$ строк, каждая из которых задает запрос. В $$$i$$$-й строке записаны три целых числа $$$t_i$$$, $$$x_i$$$ и $$$y_i$$$ ($$$1 \le t_i \le 2$$$). Если $$$t_i = 1$$$, то это запрос первого типа, $$$1 \le x_i \le 500000$$$, и $$$-1000 \le y_i \le 1000$$$. Если $$$t_i = 2$$$, то это запрос второго типа, $$$1 \le x_i \le 500000$$$, и $$$0 \le y_i &lt; x_i$$$.</p><p>Гарантируется, что во входных данных есть хотя бы один запрос типа $$$2$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса типа $$$2$$$ выведите одно целое число — ответ на этот запрос.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 1 3 4 2 3 0 2 4 3 1 4 -4 2 1 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 4 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'81248317aa3416bb',t:'MTY5NjY2NDU5Ni40ODkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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", "*2100"]
1207G
1207
G
ru
G. Инди альбом
<div class="problem-statement"><div class="header"><div class="title">G. Инди альбом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Любимая экспериментальная инди группа Мишки недавно выпустила новый альбом! У песен этого альбома есть одна общая особенность. Название каждой песни $$$s_i$$$ — одно из следующих типов:</p><ul> <li> $$$1~c$$$ — одна строчная латинская буква; </li><li> $$$2~j~c$$$ — название $$$s_j$$$ ($$$1 \le j &lt; i$$$) с приписанной к нему справа одной строчной латинской буквой. </li></ul><p>Песни пронумерованы от $$$1$$$ до $$$n$$$. Гарантируется, что первая песня всегда типа $$$1$$$.</p><p>Вове тоже интересен новый альбом, но он никак не может найти время его послушать целиком. Поэтому он решил задать Мишке несколько вопросов о нем, чтобы узнать, достойна ли какая-нибудь песня прослушивания. Все вопросы имеют одинаковый формат:</p><ul> <li> $$$i~t$$$ — посчитать количество вхождений строки $$$t$$$ в $$$s_i$$$ (название $$$i$$$-й песни альбома), как подстроки, $$$t$$$ состоит только из строчных латинских букв. </li></ul><p>И хотя Мишка не понимает, какая польза от этой информации, он старается помочь Вове. Однако вопросов так много, что он не справляется. Помогите, пожалуйста, Мише ответить на все вопросы Вовы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$) — количество песен в альбоме.</p><p>В каждой из следующих $$$n$$$ строк записано название $$$i$$$-й песни альбома в следующем формате:</p><ul> <li> $$$1~c$$$ — $$$s_i$$$ — это одна строчная латинская буква; </li><li> $$$2~j~c$$$ — $$$s_i$$$ — это название $$$s_j$$$ ($$$1 \le j &lt; i$$$) с приписанной к нему справа одной строчной латинской буквой. </li></ul><p>В следующей строке записано одно целое число $$$m$$$ ($$$1 \le m \le 4 \cdot 10^5$$$) — количество вопросов Вовы.</p><p>В каждой из следующих $$$m$$$ строк записан $$$j$$$-й вопрос Вовы в следующем формате:</p><ul> <li> $$$i~t$$$ ($$$1 \le i \le n$$$, $$$1 \le |t| \le 4 \cdot 10^5$$$) — посчитать количество вхождений строки $$$t$$$ в $$$s_i$$$ (название $$$i$$$-й песни альбома), как подстроки, $$$t$$$ состоит только из строчных латинских букв. </li></ul><p><span class="tex-font-style-bf">Гарантируется, что суммарная длина всех строк $$$t$$$ из вопросов не превосходит $$$4 \cdot 10^5$$$</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый вопрос выведите одно целое число — количество вхождений строки вопроса $$$t$$$ в название $$$i$$$-й песни альбома, как подстроки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 20 1 d 2 1 a 2 2 d 2 3 a 2 4 d 2 5 a 2 6 d 2 7 a 1 d 2 9 o 2 10 k 2 11 i 2 12 d 2 13 o 2 14 k 2 15 i 2 1 o 2 17 k 2 18 i 2 15 i 12 8 da 8 dada 8 ada 6 dada 3 dada 19 doki 19 ok 16 doki 15 doki 9 d 1 a 20 doki </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 3 2 0 1 1 2 1 1 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Названия песен из первого примера:</p><ol> <li> d </li><li> da </li><li> dad </li><li> dada </li><li> dadad </li><li> dadada </li><li> dadadad </li><li> dadadada </li><li> d </li><li> do </li><li> dok </li><li> doki </li><li> dokid </li><li> dokido </li><li> dokidok </li><li> dokidoki </li><li> do </li><li> dok </li><li> doki </li><li> dokidoki </li></ol><p>Тогда вхождения для каждого вопроса следующие:</p><ol> <li> строка «da» начинается в позициях $$$[1, 3, 5, 7]$$$ в названии «dadadada»; </li><li> строка «dada» начинается в позициях $$$[1, 3, 5]$$$ в названии «dadadada»; </li><li> строка «ada» начинается в позициях $$$[2, 4, 6]$$$ в названии «dadadada»; </li><li> строка «dada» начинается в позициях $$$[1, 3]$$$ в названии «dadada»; </li><li> нет вхождений строки «dada» в названии «dad»; </li><li> строка «doki» начинается в позиции $$$[1]$$$ в названии «doki»; </li><li> строка «ok» начинается в позиции $$$[2]$$$ в названии «doki»; </li><li> строка «doki» начинается в позициях $$$[1, 5]$$$ в названии «dokidoki»; </li><li> строка «doki» начинается в позиции $$$[1]$$$ в названии «dokidok»; </li><li> строка «d» начинается в позиции $$$[1]$$$ в названии «d»; </li><li> нет вхождений строки «a» в названии «d»; </li><li> строка «doki» начинается в позициях $$$[1, 5]$$$ в названии «dokidoki». </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="ccd4ac75bb24a8f277e276c3348fdd0c"/> <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="6ce560e12bf173a66595ca4e70e65c7ea0a69314"/> <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='ccd4ac75bb24a8f277e276c3348fdd0c'>&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%2F1207%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='ccd4ac75bb24a8f277e276c3348fdd0c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1207">Educational Codeforces Round 71 (рейтинговый для Див. 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='ccd4ac75bb24a8f277e276c3348fdd0c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1207/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Суффиксные массивы, деревья и автоматы"> строковые суфф. структуры </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Хэши, хэш-таблицы"> хэши </span> </div> <div class="roundbox borderTopRound 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='ccd4ac75bb24a8f277e276c3348fdd0c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="393977"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ccd4ac75bb24a8f277e276c3348fdd0c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="393977"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69261" title="Educational Codeforces Round 71 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9745:9746" 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/69314" title="Разбор Educational Codeforces Round 71" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9747:9748" 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/1207">Задачи</a></li> <li><a href="/contest/1207/submit">Отослать</a></li> <li><a href="/contest/1207/my">Мои посылки</a></li> <li><a href="/contest/1207/status">Статус</a></li> <li><a href="/contest/1207/hacks">Взломы</a></li> <li><a href="/contest/1207/standings">Положение</a></li> <li><a href="/contest/1207/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_90c9ea9c7d73f3a574e42259e460667865384788"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Любимая экспериментальная инди группа Мишки недавно выпустила новый альбом! У песен этого альбома есть одна общая особенность. Название каждой песни $$$s_i$$$ — одно из следующих типов:</p><ul> <li> $$$1~c$$$ — одна строчная латинская буква; </li><li> $$$2~j~c$$$ — название $$$s_j$$$ ($$$1 \le j &lt; i$$$) с приписанной к нему справа одной строчной латинской буквой. </li></ul><p>Песни пронумерованы от $$$1$$$ до $$$n$$$. Гарантируется, что первая песня всегда типа $$$1$$$.</p><p>Вове тоже интересен новый альбом, но он никак не может найти время его послушать целиком. Поэтому он решил задать Мишке несколько вопросов о нем, чтобы узнать, достойна ли какая-нибудь песня прослушивания. Все вопросы имеют одинаковый формат:</p><ul> <li> $$$i~t$$$ — посчитать количество вхождений строки $$$t$$$ в $$$s_i$$$ (название $$$i$$$-й песни альбома), как подстроки, $$$t$$$ состоит только из строчных латинских букв. </li></ul><p>И хотя Мишка не понимает, какая польза от этой информации, он старается помочь Вове. Однако вопросов так много, что он не справляется. Помогите, пожалуйста, Мише ответить на все вопросы Вовы.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \le n \le 4 \cdot 10^5$$$) — количество песен в альбоме.</p><p>В каждой из следующих $$$n$$$ строк записано название $$$i$$$-й песни альбома в следующем формате:</p><ul> <li> $$$1~c$$$ — $$$s_i$$$ — это одна строчная латинская буква; </li><li> $$$2~j~c$$$ — $$$s_i$$$ — это название $$$s_j$$$ ($$$1 \le j &lt; i$$$) с приписанной к нему справа одной строчной латинской буквой. </li></ul><p>В следующей строке записано одно целое число $$$m$$$ ($$$1 \le m \le 4 \cdot 10^5$$$) — количество вопросов Вовы.</p><p>В каждой из следующих $$$m$$$ строк записан $$$j$$$-й вопрос Вовы в следующем формате:</p><ul> <li> $$$i~t$$$ ($$$1 \le i \le n$$$, $$$1 \le |t| \le 4 \cdot 10^5$$$) — посчитать количество вхождений строки $$$t$$$ в $$$s_i$$$ (название $$$i$$$-й песни альбома), как подстроки, $$$t$$$ состоит только из строчных латинских букв. </li></ul><p><span class="tex-font-style-bf">Гарантируется, что суммарная длина всех строк $$$t$$$ из вопросов не превосходит $$$4 \cdot 10^5$$$</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый вопрос выведите одно целое число — количество вхождений строки вопроса $$$t$$$ в название $$$i$$$-й песни альбома, как подстроки.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 20 1 d 2 1 a 2 2 d 2 3 a 2 4 d 2 5 a 2 6 d 2 7 a 1 d 2 9 o 2 10 k 2 11 i 2 12 d 2 13 o 2 14 k 2 15 i 2 1 o 2 17 k 2 18 i 2 15 i 12 8 da 8 dada 8 ada 6 dada 3 dada 19 doki 19 ok 16 doki 15 doki 9 d 1 a 20 doki </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 3 2 0 1 1 2 1 1 0 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Названия песен из первого примера:</p><ol> <li> d </li><li> da </li><li> dad </li><li> dada </li><li> dadad </li><li> dadada </li><li> dadadad </li><li> dadadada </li><li> d </li><li> do </li><li> dok </li><li> doki </li><li> dokid </li><li> dokido </li><li> dokidok </li><li> dokidoki </li><li> do </li><li> dok </li><li> doki </li><li> dokidoki </li></ol><p>Тогда вхождения для каждого вопроса следующие:</p><ol> <li> строка «da» начинается в позициях $$$[1, 3, 5, 7]$$$ в названии «dadadada»; </li><li> строка «dada» начинается в позициях $$$[1, 3, 5]$$$ в названии «dadadada»; </li><li> строка «ada» начинается в позициях $$$[2, 4, 6]$$$ в названии «dadadada»; </li><li> строка «dada» начинается в позициях $$$[1, 3]$$$ в названии «dadada»; </li><li> нет вхождений строки «dada» в названии «dad»; </li><li> строка «doki» начинается в позиции $$$[1]$$$ в названии «doki»; </li><li> строка «ok» начинается в позиции $$$[2]$$$ в названии «doki»; </li><li> строка «doki» начинается в позициях $$$[1, 5]$$$ в названии «dokidoki»; </li><li> строка «doki» начинается в позиции $$$[1]$$$ в названии «dokidok»; </li><li> строка «d» начинается в позиции $$$[1]$$$ в названии «d»; </li><li> нет вхождений строки «a» в названии «d»; </li><li> строка «doki» начинается в позициях $$$[1, 5]$$$ в названии «dokidoki». </li></ol></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 10:43: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:'81248327bc6000a5',t:'MTY5NjY2NDU5Ny44NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u043c\u0430\u0441\u0441\u0438\u0432\u044b, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u0438 \u0430\u0432\u0442\u043e\u043c\u0430\u0442\u044b", "\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.", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\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", "\u0445\u044d\u0448\u0438", "*2700"]
1208A
1208
A
ru
A. XORиначчи
<div class="problem-statement"><div class="header"><div class="title">A. XORиначчи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дженгиз недавно узнал, что такое числа Фибоначчи, и сейчас он занимается изучением алгоритмов для их поиска. Вскоре ему стало скучно читать про них, и он придумал новый тип чисел, который он назвал числами <span class="tex-font-style-it">XORиначчи</span>. Он определил их следующим образом:</p><ul> <li> $$$f(0) = a$$$; </li><li> $$$f(1) = b$$$; </li><li> $$$f(n) = f(n-1) \oplus f(n-2)$$$ при $$$n &gt; 1$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. </li></ul><p>Вам даны три целых числа $$$a$$$, $$$b$$$ и $$$n$$$, найдите $$$f(n)$$$.</p><p>Вам нужно решить $$$T$$$ независимых тестовых примеров.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Ввод состоит из нескольких тестовых примеров.</p><p>Первая строка ввода содержит целое число $$$T$$$ ($$$1 \le T \le 10^3$$$), количество тестовых примеров.</p><p>Каждая из следующих $$$T$$$ строк содержит три целых числа, разделенных пробелами: $$$a$$$, $$$b$$$ и $$$n$$$ ($$$0 \le a, b, n \le 10^9$$$) соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста выведите $$$f(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 4 2 4 5 0 325 265 1231232 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 4 76 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4550a868e02ee1301761f31e2167d181"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='4550a868e02ee1301761f31e2167d181'>&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%2F1208%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='4550a868e02ee1301761f31e2167d181'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='4550a868e02ee1301761f31e2167d181'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='4550a868e02ee1301761f31e2167d181'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395876"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4550a868e02ee1301761f31e2167d181'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395876"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d100ea60bd3dd6f9da05b0fe15a4d639d2873bba"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. XORиначчи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дженгиз недавно узнал, что такое числа Фибоначчи, и сейчас он занимается изучением алгоритмов для их поиска. Вскоре ему стало скучно читать про них, и он придумал новый тип чисел, который он назвал числами <span class="tex-font-style-it">XORиначчи</span>. Он определил их следующим образом:</p><ul> <li> $$$f(0) = a$$$; </li><li> $$$f(1) = b$$$; </li><li> $$$f(n) = f(n-1) \oplus f(n-2)$$$ при $$$n &gt; 1$$$, где $$$\oplus$$$ обозначает операцию <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">побитового исключающего ИЛИ</a>. </li></ul><p>Вам даны три целых числа $$$a$$$, $$$b$$$ и $$$n$$$, найдите $$$f(n)$$$.</p><p>Вам нужно решить $$$T$$$ независимых тестовых примеров.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Ввод состоит из нескольких тестовых примеров.</p><p>Первая строка ввода содержит целое число $$$T$$$ ($$$1 \le T \le 10^3$$$), количество тестовых примеров.</p><p>Каждая из следующих $$$T$$$ строк содержит три целых числа, разделенных пробелами: $$$a$$$, $$$b$$$ и $$$n$$$ ($$$0 \le a, b, n \le 10^9$$$) соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого теста выведите $$$f(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 4 2 4 5 0 325 265 1231232 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 4 76 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$f(2) = f(0) \oplus f(1) = 3 \oplus 4 = 7$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483304b243a7d',t:'MTY5NjY2NDU5OS4yOTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"]
1208B
1208
B
ru
B. Уникальность
<div class="problem-statement"><div class="header"><div class="title">B. Уникальность</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Дан массив $$$a_{1}, a_{2}, \ldots, a_{n}$$$. Вы можете удалить из него <span class="tex-font-style-bf">не более одного</span> подотрезка. Оставшиеся элементы должны быть попарно различны.</p><p>Другими словами, <span class="tex-font-style-bf">не более одного</span> раза вы можете выбрать два целых числа $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) и удалить элементы $$$a_l, a_{l+1}, \ldots, a_r$$$ из массива. Оставшиеся в массиве элементы должны быть попарно различны. </p><p>Найдите минимальный размер подотрезка, при удалении которого все элементы массива будут попарно различными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — количество элементов массива.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальный размер подотрезка при удалении которого все элементы массива будут попарно различными. Если элементы массива попарно различны и без удаления подотрезка, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 4 1 4 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все элементы исходно различны, поэтому удалять подотрезок не требуется.</p><p>Во втором примере вы можете удалить подотрезок с индексами от $$$2$$$ до $$$3$$$.</p><p>В третьем примере вы можете удалить подотрезок с индексами от $$$1$$$ до $$$2$$$, или с индексами от $$$2$$$ до $$$3$$$, или с индексами от $$$3$$$ до $$$4$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1fdd4dcf5e04d69cc8412a54badd5744"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='1fdd4dcf5e04d69cc8412a54badd5744'>&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%2F1208%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='1fdd4dcf5e04d69cc8412a54badd5744'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='1fdd4dcf5e04d69cc8412a54badd5744'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='1fdd4dcf5e04d69cc8412a54badd5744'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395877"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1fdd4dcf5e04d69cc8412a54badd5744'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395877"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4d2a8fddffa1a3dd341d56241fedda5dc8e4b02c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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_{1}, a_{2}, \ldots, a_{n}$$$. Вы можете удалить из него <span class="tex-font-style-bf">не более одного</span> подотрезка. Оставшиеся элементы должны быть попарно различны.</p><p>Другими словами, <span class="tex-font-style-bf">не более одного</span> раза вы можете выбрать два целых числа $$$l$$$ и $$$r$$$ ($$$1 \leq l \leq r \leq n$$$) и удалить элементы $$$a_l, a_{l+1}, \ldots, a_r$$$ из массива. Оставшиеся в массиве элементы должны быть попарно различны. </p><p>Найдите минимальный размер подотрезка, при удалении которого все элементы массива будут попарно различными.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит целое число $$$n$$$ ($$$1 \le n \le 2000$$$) — количество элементов массива.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$a_{1}, a_{2}, \ldots, a_{n}$$$ ($$$1 \le a_{i} \le 10^{9}$$$) — элементы массива.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальный размер подотрезка при удалении которого все элементы массива будут попарно различными. Если элементы массива попарно различны и без удаления подотрезка, выведите $$$0$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 1 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 1 4 1 4 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все элементы исходно различны, поэтому удалять подотрезок не требуется.</p><p>Во втором примере вы можете удалить подотрезок с индексами от $$$2$$$ до $$$3$$$.</p><p>В третьем примере вы можете удалить подотрезок с индексами от $$$1$$$ до $$$2$$$, или с индексами от $$$2$$$ до $$$3$$$, или с индексами от $$$3$$$ до $$$4$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483394a364979',t:'MTY5NjY2NDYwMC42NjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1500"]
1208C
1208
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-it">магической</span> таблицой кадратную матрицу размера $$$n \times n$$$, в которой выполняются следующие условия. </p><ul> <li> Все целые числа от $$$0$$$ до $$$(n^2 - 1)$$$ включительно встречаются в таблице <span class="tex-font-style-bf">ровно один раз</span>. </li><li> <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">Побитовое исключающее ИЛИ</a> всех элементов в строке или в столбце должно быть одинаковым для всех строк и столбцов. </li></ul><p>Вам дано целое число $$$n$$$, которое <span class="tex-font-style-bf">делится на $$$4$$$</span>. Постройте <span class="tex-font-style-it">магическую</span> таблицу размера $$$n \times n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано целое число $$$n$$$ ($$$4 \leq n \leq 1000$$$). Гарантируется, что $$$n$$$ делится на $$$4$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите <span class="tex-font-style-it">магическую</span> таблицу, т.е. $$$n$$$ строк, в $$$i$$$-й из которых должно быть записано $$$n$$$ целых числ, разделенных пробелами, описывающих $$$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> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 9 1 13 3 12 7 5 0 2 4 11 6 10 15 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 19 55 11 39 32 36 4 52 51 7 35 31 12 48 28 20 43 23 59 15 0 8 16 44 3 47 27 63 24 40 60 56 34 38 6 54 17 53 9 37 14 50 30 22 49 5 33 29 2 10 18 46 41 21 57 13 26 42 62 58 1 45 25 61</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере XOR в каждой строке и в каждом столбце равен $$$13$$$.</p><p>Во втором примере XOR в каждой строке и в каждом столбце равен $$$60$$$.</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="7c6d8d4c48b565a4e67de0308897b069"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='7c6d8d4c48b565a4e67de0308897b069'>&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%2F1208%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='7c6d8d4c48b565a4e67de0308897b069'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='7c6d8d4c48b565a4e67de0308897b069'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='7c6d8d4c48b565a4e67de0308897b069'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395878"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7c6d8d4c48b565a4e67de0308897b069'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395878"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_62d352dd112c57572ae51fc9ef7160849018386b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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-it">магической</span> таблицой кадратную матрицу размера $$$n \times n$$$, в которой выполняются следующие условия. </p><ul> <li> Все целые числа от $$$0$$$ до $$$(n^2 - 1)$$$ включительно встречаются в таблице <span class="tex-font-style-bf">ровно один раз</span>. </li><li> <a href="https://ru.wikipedia.org/wiki/Сложение_по_модулю_2">Побитовое исключающее ИЛИ</a> всех элементов в строке или в столбце должно быть одинаковым для всех строк и столбцов. </li></ul><p>Вам дано целое число $$$n$$$, которое <span class="tex-font-style-bf">делится на $$$4$$$</span>. Постройте <span class="tex-font-style-it">магическую</span> таблицу размера $$$n \times n$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано целое число $$$n$$$ ($$$4 \leq n \leq 1000$$$). Гарантируется, что $$$n$$$ делится на $$$4$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите <span class="tex-font-style-it">магическую</span> таблицу, т.е. $$$n$$$ строк, в $$$i$$$-й из которых должно быть записано $$$n$$$ целых числ, разделенных пробелами, описывающих $$$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> 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 9 1 13 3 12 7 5 0 2 4 11 6 10 15 14</pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 19 55 11 39 32 36 4 52 51 7 35 31 12 48 28 20 43 23 59 15 0 8 16 44 3 47 27 63 24 40 60 56 34 38 6 54 17 53 9 37 14 50 30 22 49 5 33 29 2 10 18 46 41 21 57 13 26 42 62 58 1 45 25 61</pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере XOR в каждой строке и в каждом столбце равен $$$13$$$.</p><p>Во втором примере XOR в каждой строке и в каждом столбце равен $$$60$$$.</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 10:43: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:'81248341cc4116b7',t:'MTY5NjY2NDYwMi4wMTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1800"]
1208D
1208
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_{1},p_{2}, \ldots,p_{n}$$$ называется перестановкой, если она содержит каждое число от $$$1$$$ до $$$n$$$ ровно один раз. Например, следующие последовательности перестановки: $$$[3,1,2], [1], [1,2,3,4,5]$$$ и $$$[4,3,1,2]$$$. А следующие последовательности не являются перестановками: $$$[2], [1,1], [2,3,4]$$$.</p><p>Загадана перестановка длины $$$n$$$.</p><p>Для каждого индекса $$$i$$$ вам дано $$$s_{i}$$$, равное сумме всех таких $$$p_{j}$$$, что $$$j &lt; i$$$ и $$$p_{j} &lt; p_{i}$$$. Иначе говоря, $$$s_i$$$ — это сумма всех элементов до $$$i$$$-го элемента, которые меньше $$$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$$$ целых чисел $$$s_{1}, s_{2}, \ldots, s_{n}$$$ ($$$0 \le s_{i} \le \frac{n(n-1)}{2}$$$).</p><p>Гарантируется, что $$$s$$$ соответствует корректной перестановке длины $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$p_{1}, p_{2}, \ldots, p_{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> 3 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 3 2 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере для каждого $$$i$$$ не существует позиции $$$j$$$, удовлетворяющей обоим условиям, соответственно $$$s_i$$$ всегда равен $$$0$$$.</p><p>Во втором примере для $$$i = 2$$$ позиция $$$j = 1$$$ удовлетворяет условиям, так что $$$s_2 = p_1$$$.</p><p>В третьем примере для $$$i = 2, 3, 4$$$ только позиция $$$j = 1$$$ удовлетворяет условиям, так что $$$s_2 = s_3 = s_4 = 1$$$. Для $$$i = 5$$$ возможны все позиции $$$j = 1, 2, 3, 4$$$, и $$$s_5 = p_1 + p_2 + p_3 + p_4 = 10$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e8f4d13a070e6faa4df9d498186200c9"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='e8f4d13a070e6faa4df9d498186200c9'>&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%2F1208%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='e8f4d13a070e6faa4df9d498186200c9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='e8f4d13a070e6faa4df9d498186200c9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='e8f4d13a070e6faa4df9d498186200c9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395879"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e8f4d13a070e6faa4df9d498186200c9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395879"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9c64b0a32c1d4dfc9451902071ea3ad00bdae418"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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_{1},p_{2}, \ldots,p_{n}$$$ называется перестановкой, если она содержит каждое число от $$$1$$$ до $$$n$$$ ровно один раз. Например, следующие последовательности перестановки: $$$[3,1,2], [1], [1,2,3,4,5]$$$ и $$$[4,3,1,2]$$$. А следующие последовательности не являются перестановками: $$$[2], [1,1], [2,3,4]$$$.</p><p>Загадана перестановка длины $$$n$$$.</p><p>Для каждого индекса $$$i$$$ вам дано $$$s_{i}$$$, равное сумме всех таких $$$p_{j}$$$, что $$$j &lt; i$$$ и $$$p_{j} &lt; p_{i}$$$. Иначе говоря, $$$s_i$$$ — это сумма всех элементов до $$$i$$$-го элемента, которые меньше $$$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$$$ целых чисел $$$s_{1}, s_{2}, \ldots, s_{n}$$$ ($$$0 \le s_{i} \le \frac{n(n-1)}{2}$$$).</p><p>Гарантируется, что $$$s$$$ соответствует корректной перестановке длины $$$n$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ целых чисел $$$p_{1}, p_{2}, \ldots, p_{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> 3 0 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 0 1 1 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 4 3 2 5 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере для каждого $$$i$$$ не существует позиции $$$j$$$, удовлетворяющей обоим условиям, соответственно $$$s_i$$$ всегда равен $$$0$$$.</p><p>Во втором примере для $$$i = 2$$$ позиция $$$j = 1$$$ удовлетворяет условиям, так что $$$s_2 = p_1$$$.</p><p>В третьем примере для $$$i = 2, 3, 4$$$ только позиция $$$j = 1$$$ удовлетворяет условиям, так что $$$s_2 = s_3 = s_4 = 1$$$. Для $$$i = 5$$$ возможны все позиции $$$j = 1, 2, 3, 4$$$, и $$$s_5 = p_1 + p_2 + p_3 + p_4 = 10$$$.</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 10:43: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:'8124834a3faf16df',t:'MTY5NjY2NDYwMy4zODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1900"]
1208E
1208
E
ru
E. Пусть скользят
<div class="problem-statement"><div class="header"><div class="title">E. Пусть скользят</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$n$$$ массивов, которые могут иметь разные длины. Также вам дана таблица с $$$w$$$ столбцами и $$$n$$$ строками. $$$i$$$-й массив горизонтально расположен в $$$i$$$-й строке. Вы можете двигать каждый массив внутри его строки, но он должен всегда занимать подряд идущие клетки и лежать полностью внутри таблицы.</p><p>Вам нужно найти наибольшую возможную сумму чисел в $$$j$$$-м столбце для каждого $$$j$$$ от $$$1$$$ до $$$w$$$ независимо.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/beff32ef982f7bd287b1248c57edf3c65609e45f.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Оптимальные расположения для столбцов $$$1$$$, $$$2$$$ и $$$3$$$ изображены на изображениях слева направо.</span> </center><p>Обратите внимание, что вы можете исключить любой массив из столбца (но только если он останется внутри своей строки). В таком случае значение полагается равным нулю.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано два целых числа $$$n$$$ ($$$1 \le n \le 10^{6}$$$) и $$$w$$$ ($$$1 \le w \le 10^{6}$$$) — количество массивов и ширина таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит целое число $$$l_{i}$$$ ($$$1 \le l_{i} \le w$$$) — длина $$$i$$$-го массива, за которой следуют $$$l_{i}$$$ целых чисел $$$a_{i1}, a_{i2}, \ldots, a_{il_i}$$$ ($$$-10^{9} \le a_{ij} \le 10^{9}$$$) — элементы массива.</p><p>Суммарная длина массивов не превосходит $$$10^{6}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$w$$$ целых чисел, $$$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 3 3 2 4 8 2 2 5 2 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 15 16 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 7 8 1 -8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображения для первого примера находятся в условии.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="effe36a56e32c31cdeee2eaa2b3a7c1a"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='effe36a56e32c31cdeee2eaa2b3a7c1a'>&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%2F1208%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='effe36a56e32c31cdeee2eaa2b3a7c1a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='effe36a56e32c31cdeee2eaa2b3a7c1a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='effe36a56e32c31cdeee2eaa2b3a7c1a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395880"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='effe36a56e32c31cdeee2eaa2b3a7c1a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395880"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_395134e02a45ddf9136fee0051bbc0acda56d128"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано $$$n$$$ массивов, которые могут иметь разные длины. Также вам дана таблица с $$$w$$$ столбцами и $$$n$$$ строками. $$$i$$$-й массив горизонтально расположен в $$$i$$$-й строке. Вы можете двигать каждый массив внутри его строки, но он должен всегда занимать подряд идущие клетки и лежать полностью внутри таблицы.</p><p>Вам нужно найти наибольшую возможную сумму чисел в $$$j$$$-м столбце для каждого $$$j$$$ от $$$1$$$ до $$$w$$$ независимо.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/beff32ef982f7bd287b1248c57edf3c65609e45f.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Оптимальные расположения для столбцов $$$1$$$, $$$2$$$ и $$$3$$$ изображены на изображениях слева направо.</span> </center><p>Обратите внимание, что вы можете исключить любой массив из столбца (но только если он останется внутри своей строки). В таком случае значение полагается равным нулю.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано два целых числа $$$n$$$ ($$$1 \le n \le 10^{6}$$$) и $$$w$$$ ($$$1 \le w \le 10^{6}$$$) — количество массивов и ширина таблицы.</p><p>Каждая из следующих $$$n$$$ строк содержит целое число $$$l_{i}$$$ ($$$1 \le l_{i} \le w$$$) — длина $$$i$$$-го массива, за которой следуют $$$l_{i}$$$ целых чисел $$$a_{i1}, a_{i2}, \ldots, a_{il_i}$$$ ($$$-10^{9} \le a_{ij} \le 10^{9}$$$) — элементы массива.</p><p>Суммарная длина массивов не превосходит $$$10^{6}$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$w$$$ целых чисел, $$$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 3 3 2 4 8 2 2 5 2 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 10 15 16 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 2 7 8 1 -8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Изображения для первого примера находятся в условии.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'81248352df3d76b5',t:'MTY5NjY2NDYwNC43NDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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"]
["\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", "*2200"]
1208F
1208
F
ru
F. Биты и выбор
<div class="problem-statement"><div class="header"><div class="title">F. Биты и выбор</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вам нужно найти наибольшее возможное значение $$$a_{i} | ( a_{j} \&amp; a_{k} )$$$ по всем таким тройкам $$$(i,j,k)$$$, что $$$i &lt; j &lt; k$$$.</p><p>Здесь $$$\&amp;$$$ обозначает операцию <a href="https://bit.ly/2LBLVWv">побитового И</a>, а $$$|$$$ обозначает операцию <a href="http://bitly.com/2JQkyd6">побитового ИЛИ</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано целое число $$$n$$$ ($$$3 \le n \le 10^{6}$$$) — размер массива $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, разделенных пробелами $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_{i} \le 2 \cdot 10^{6}$$$) — массив $$$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> 3 2 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 8 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере единственная возможная тройка это $$$(1, 2, 3)$$$. Таким образом, ответ равен $$$2 | (4 \&amp; 6) = 6$$$.</p><p>Во втором примере есть $$$4$$$ возможные тройки: </p><ol> <li> $$$(1, 2, 3)$$$, значение которой $$$2|(8\&amp;4) = 2$$$. </li><li> $$$(1, 2, 4)$$$, значение которой $$$2|(8\&amp;7) = 2$$$. </li><li> $$$(1, 3, 4)$$$, значение которой $$$2|(4\&amp;7) = 6$$$. </li><li> $$$(2, 3, 4)$$$, значение которой $$$8|(4\&amp;7) = 12$$$. </li></ol><p>Таким образом максимальное значение равно $$$12$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="62ca4f3e77ceadfda8ed75a77d89e6df"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='62ca4f3e77ceadfda8ed75a77d89e6df'>&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%2F1208%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='62ca4f3e77ceadfda8ed75a77d89e6df'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='62ca4f3e77ceadfda8ed75a77d89e6df'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='62ca4f3e77ceadfda8ed75a77d89e6df'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395881"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='62ca4f3e77ceadfda8ed75a77d89e6df'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395881"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cbae89a0a0592caf510d11b8201c185798014b82"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам дан массив $$$a$$$ из $$$n$$$ целых чисел.</p><p>Вам нужно найти наибольшее возможное значение $$$a_{i} | ( a_{j} \&amp; a_{k} )$$$ по всем таким тройкам $$$(i,j,k)$$$, что $$$i &lt; j &lt; k$$$.</p><p>Здесь $$$\&amp;$$$ обозначает операцию <a href="https://bit.ly/2LBLVWv">побитового И</a>, а $$$|$$$ обозначает операцию <a href="http://bitly.com/2JQkyd6">побитового ИЛИ</a>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записано целое число $$$n$$$ ($$$3 \le n \le 10^{6}$$$) — размер массива $$$a$$$.</p><p>Во второй строке записаны $$$n$$$ целых чисел, разделенных пробелами $$$a_1$$$, $$$a_2$$$, ..., $$$a_n$$$ ($$$0 \le a_{i} \le 2 \cdot 10^{6}$$$) — массив $$$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> 3 2 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 8 4 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере единственная возможная тройка это $$$(1, 2, 3)$$$. Таким образом, ответ равен $$$2 | (4 \&amp; 6) = 6$$$.</p><p>Во втором примере есть $$$4$$$ возможные тройки: </p><ol> <li> $$$(1, 2, 3)$$$, значение которой $$$2|(8\&amp;4) = 2$$$. </li><li> $$$(1, 2, 4)$$$, значение которой $$$2|(8\&amp;7) = 2$$$. </li><li> $$$(1, 3, 4)$$$, значение которой $$$2|(4\&amp;7) = 6$$$. </li><li> $$$(2, 3, 4)$$$, значение которой $$$8|(4\&amp;7) = 12$$$. </li></ol><p>Таким образом максимальное значение равно $$$12$$$.</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 10:43: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:'8124835b6f3216af',t:'MTY5NjY2NDYwNi4xMDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\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", "*2600"]
1208G
1208
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><p>Вам даны два целых числа $$$n$$$ и $$$k$$$.</p><p>Вам нужно построить $$$k$$$ правильных многоугольников с общей <a href="https://ru.wikipedia.org/wiki/Описанная_окружность">описанной окружностью</a> с <span class="tex-font-style-bf">различными</span> количествами сторон $$$l$$$ от $$$3$$$ до $$$n$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ca6695475048e813597541ede18588574e39aef.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Изображение к первому примеру.</span> </center><p>Вы можете вращать их, чтобы минимизировать количество различных точек на окружности. Найдите минимальное количество таких точек.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записаны два целых числа $$$n$$$ и $$$k$$$ ($$$3 \le n \le 10^{6}$$$, $$$1 \le k \le n-2$$$) — максимальное количество сторон у многоугольника и количество многоугольников, которое нужно построить, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное число точек на окружности, необходимых для размещения $$$k$$$ многоугольников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 200 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 708 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$n = 6$$$ и $$$k = 2$$$. Таким образом, есть $$$4$$$ многоугольника с количествами сторон $$$3$$$, $$$4$$$, $$$5$$$ и $$$6$$$ из которых нужно выбирать, и если выбрать треугольник и шестиугольник, получится картинка из условия.</p><p>Таким образом, минимальное необходимое количество точек на круге $$$6$$$, что также минимально по всем возможных множествам.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="19c8fc5a0054aa1a94c02c12cb6ab572"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='19c8fc5a0054aa1a94c02c12cb6ab572'>&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%2F1208%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='19c8fc5a0054aa1a94c02c12cb6ab572'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='19c8fc5a0054aa1a94c02c12cb6ab572'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='19c8fc5a0054aa1a94c02c12cb6ab572'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395882"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='19c8fc5a0054aa1a94c02c12cb6ab572'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395882"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2a3938ebbd2ba83f934c682e902e865b31263e63"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><p>Вам даны два целых числа $$$n$$$ и $$$k$$$.</p><p>Вам нужно построить $$$k$$$ правильных многоугольников с общей <a href="https://ru.wikipedia.org/wiki/Описанная_окружность">описанной окружностью</a> с <span class="tex-font-style-bf">различными</span> количествами сторон $$$l$$$ от $$$3$$$ до $$$n$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/8ca6695475048e813597541ede18588574e39aef.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Изображение к первому примеру.</span> </center><p>Вы можете вращать их, чтобы минимизировать количество различных точек на окружности. Найдите минимальное количество таких точек.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке ввода записаны два целых числа $$$n$$$ и $$$k$$$ ($$$3 \le n \le 10^{6}$$$, $$$1 \le k \le n-2$$$) — максимальное количество сторон у многоугольника и количество многоугольников, которое нужно построить, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное число точек на окружности, необходимых для размещения $$$k$$$ многоугольников.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 200 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 708 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$n = 6$$$ и $$$k = 2$$$. Таким образом, есть $$$4$$$ многоугольника с количествами сторон $$$3$$$, $$$4$$$, $$$5$$$ и $$$6$$$ из которых нужно выбирать, и если выбрать треугольник и шестиугольник, получится картинка из условия.</p><p>Таким образом, минимальное необходимое количество точек на круге $$$6$$$, что также минимально по всем возможных множествам.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'81248363cdfa0004',t:'MTY5NjY2NDYwNy40MjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2800"]
1208H
1208
H
ru
H. Красно-синее дерево
<div class="problem-statement"><div class="header"><div class="title">H. Красно-синее дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано дерево с $$$n$$$ вершинами. Дерево подвешено за вершину $$$1$$$, которая не считается листом не зависимо от ее степени.</p><p>Каждый лист покрашен в один из двух цветов: <span class="tex-font-style-it">красный</span> или <span class="tex-font-style-it">синий</span>. Листовая вершина с номером $$$v$$$ исходно имеет цвет $$$s_{v}$$$.</p><p>Цвет каждой из внутренней вершины (включая корень) определятся следующим образом. </p><ul> <li> Обозначим за $$$b$$$ количество <span class="tex-font-style-it">синих</span> непосредственных детей, и за $$$r$$$ количество <span class="tex-font-style-it">красных</span> непосредственных детей данной вершины. </li><li> Тогда цвет этой вершины <span class="tex-font-style-it">синий</span> тогда и только тогда, когда $$$b - r \ge k$$$, иначе он <span class="tex-font-style-it">красный</span>. </li></ul><p>Число $$$k$$$ это параметр, одинаковый для всех вершин.</p><p>Вам необходимо обработать запросы следующих типов: </p><ul> <li> <span class="tex-font-style-tt">1 v</span>: вывести цвет вершины $$$v$$$; </li><li> <span class="tex-font-style-tt">2 v c</span>: изменить цвет листа $$$v$$$ на $$$c$$$ ($$$c = 0$$$ означает красный, $$$c = 1$$$ означает синий); </li><li> <span class="tex-font-style-tt">3 h</span>: изменить текущее значение $$$k$$$ на $$$h$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^{5}$$$, $$$-n \le k \le n$$$) — количество вершин и исходное значение $$$k$$$.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), описывающих, что есть ребро, соединяющее вершины $$$u$$$ и $$$v$$$.</p><p>Следующая строка состоит из $$$n$$$ целых чисел, разделенных пробелами — исходный массив $$$s$$$ ($$$-1 \le s_i \le 1$$$). $$$s_{i} = 0$$$ означает, что цвет вершины $$$i$$$ красный. $$$s_{i} = 1$$$ означает, что цвет вершины $$$i$$$ синий. $$$s_{i} = -1$$$ означает, что вершина $$$i$$$ не является листом.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 10^5$$$), количество запросов.</p><p>Затем следуют $$$q$$$ строк, каждая содержит запрос, который необходимо обработать: </p><ul> <li> <span class="tex-font-style-tt">1 v</span> ($$$1 \le v \le n$$$): вывести цвет вершины $$$v$$$; </li><li> <span class="tex-font-style-tt">2 v c</span> ($$$1 \le v \le n$$$, $$$c = 0$$$ or $$$c = 1$$$): изменить цвет листа $$$v$$$ на $$$c$$$ ($$$c = 0$$$ означает красный, $$$c = 1$$$ означает синий). Гарантируется, что $$$v$$$ это лист; </li><li> <span class="tex-font-style-tt">3 h</span> ($$$-n \le h \le n$$$): изменить текущее значение $$$k$$$ на $$$h$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса первого типа выведите $$$0$$$, если цвет вершины $$$v$$$ красный, и $$$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 2 1 2 1 3 2 4 2 5 -1 -1 0 1 0 9 1 1 1 2 3 -2 1 1 1 2 3 1 2 5 1 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 1 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <span class="tex-font-size-small"><p>(i) Исходное дерево</p><p>(ii) Дерево после 3-го запроса</p><p>(iii) Дерево после 7-го запроса</p><p> </p></span> <img class="tex-graphics" src="https://espresso.codeforces.com/bc29ddf3b593a851cafc7b84e68af525b3b20c82.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="2490be0f9584a2a61bd80a4eccf998b9"/> <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="081c4e955c5beca6a8b7bec526675d24135ae9e5"/> <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='2490be0f9584a2a61bd80a4eccf998b9'>&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%2F1208%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='2490be0f9584a2a61bd80a4eccf998b9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1208">Manthan, Codefest 19 (open for everyone, rated, Div. 1 + 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='2490be0f9584a2a61bd80a4eccf998b9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1208/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='2490be0f9584a2a61bd80a4eccf998b9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="395883"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2490be0f9584a2a61bd80a4eccf998b9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="395883"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69323" title="Manthan — Codefest&#39;19" target="_blank">Manthan — Codefest'19 <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9262" resourceName="Manthan — Codefest&#39;19" 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="https://codeforces.com/blog/entry/69357" title="69357" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9268" resourceName="69357" 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/1208">Задачи</a></li> <li><a href="/contest/1208/submit">Отослать</a></li> <li><a href="/contest/1208/my">Мои посылки</a></li> <li><a href="/contest/1208/status">Статус</a></li> <li><a href="/contest/1208/hacks">Взломы</a></li> <li><a href="/contest/1208/room/1">Комната</a></li> <li><a href="/contest/1208/standings">Положение</a></li> <li><a href="/contest/1208/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bfff1266327e2cdda2636e3cd2e10efbfb2eb2d8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Красно-синее дерево</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дано дерево с $$$n$$$ вершинами. Дерево подвешено за вершину $$$1$$$, которая не считается листом не зависимо от ее степени.</p><p>Каждый лист покрашен в один из двух цветов: <span class="tex-font-style-it">красный</span> или <span class="tex-font-style-it">синий</span>. Листовая вершина с номером $$$v$$$ исходно имеет цвет $$$s_{v}$$$.</p><p>Цвет каждой из внутренней вершины (включая корень) определятся следующим образом. </p><ul> <li> Обозначим за $$$b$$$ количество <span class="tex-font-style-it">синих</span> непосредственных детей, и за $$$r$$$ количество <span class="tex-font-style-it">красных</span> непосредственных детей данной вершины. </li><li> Тогда цвет этой вершины <span class="tex-font-style-it">синий</span> тогда и только тогда, когда $$$b - r \ge k$$$, иначе он <span class="tex-font-style-it">красный</span>. </li></ul><p>Число $$$k$$$ это параметр, одинаковый для всех вершин.</p><p>Вам необходимо обработать запросы следующих типов: </p><ul> <li> <span class="tex-font-style-tt">1 v</span>: вывести цвет вершины $$$v$$$; </li><li> <span class="tex-font-style-tt">2 v c</span>: изменить цвет листа $$$v$$$ на $$$c$$$ ($$$c = 0$$$ означает красный, $$$c = 1$$$ означает синий); </li><li> <span class="tex-font-style-tt">3 h</span>: изменить текущее значение $$$k$$$ на $$$h$$$. </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^{5}$$$, $$$-n \le k \le n$$$) — количество вершин и исходное значение $$$k$$$.</p><p>Каждая из следующих $$$n - 1$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u,v \le n$$$), описывающих, что есть ребро, соединяющее вершины $$$u$$$ и $$$v$$$.</p><p>Следующая строка состоит из $$$n$$$ целых чисел, разделенных пробелами — исходный массив $$$s$$$ ($$$-1 \le s_i \le 1$$$). $$$s_{i} = 0$$$ означает, что цвет вершины $$$i$$$ красный. $$$s_{i} = 1$$$ означает, что цвет вершины $$$i$$$ синий. $$$s_{i} = -1$$$ означает, что вершина $$$i$$$ не является листом.</p><p>Следующая строка содержит целое число $$$q$$$ ($$$1 \le q \le 10^5$$$), количество запросов.</p><p>Затем следуют $$$q$$$ строк, каждая содержит запрос, который необходимо обработать: </p><ul> <li> <span class="tex-font-style-tt">1 v</span> ($$$1 \le v \le n$$$): вывести цвет вершины $$$v$$$; </li><li> <span class="tex-font-style-tt">2 v c</span> ($$$1 \le v \le n$$$, $$$c = 0$$$ or $$$c = 1$$$): изменить цвет листа $$$v$$$ на $$$c$$$ ($$$c = 0$$$ означает красный, $$$c = 1$$$ означает синий). Гарантируется, что $$$v$$$ это лист; </li><li> <span class="tex-font-style-tt">3 h</span> ($$$-n \le h \le n$$$): изменить текущее значение $$$k$$$ на $$$h$$$. </li></ul></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса первого типа выведите $$$0$$$, если цвет вершины $$$v$$$ красный, и $$$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 2 1 2 1 3 2 4 2 5 -1 -1 0 1 0 9 1 1 1 2 3 -2 1 1 1 2 3 1 2 5 1 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 1 1 0 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <span class="tex-font-size-small"><p>(i) Исходное дерево</p><p>(ii) Дерево после 3-го запроса</p><p>(iii) Дерево после 7-го запроса</p><p> </p></span> <img class="tex-graphics" src="https://espresso.codeforces.com/bc29ddf3b593a851cafc7b84e68af525b3b20c82.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=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 10:43: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:'8124836bf9f203dd',t:'MTY5NjY2NDYwOC43MzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "\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"]
1209A
1209
A
ru
A. Раскрашивание чисел
<div class="problem-statement"><div class="header"><div class="title">A. Раскрашивание чисел</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дана последовательность целых чисел $$$a_1, a_2, \dots, a_n$$$. Вам нужно раскрасить элементы, так чтобы: </p><ul> <li> Если мы рассмотрим произвольный цвет, то все элементы этого цвета должны делиться на минимальный элемент этого цвета. </li><li> Количество использованных цветов было бы минимально возможным. </li></ul><p>Например, можно покрасить элементы $$$[40, 10, 60]$$$ в один цвет, так как они все делятся на $$$10$$$. Каждый из цветов можно использовать произвольное количество раз (в частности, разрешается использовать любой цвет ровно один раз). Элементы, покрашенные в один цвет, не обязаны идти подряд.</p><p>Например, если $$$a=[6, 2, 3, 4, 12]$$$, то нужно использовать два цвета: можно покрасить $$$6$$$, $$$3$$$, $$$12$$$ в первый цвет ($$$6$$$, $$$3$$$ и $$$12$$$ делятся на $$$3$$$), а $$$2$$$ и $$$4$$$ во второй цвет ($$$2$$$ и $$$4$$$ делятся на $$$2$$$). Например, если $$$a=[10, 7, 15]$$$, то нужно $$$3$$$ цвета (следует покрасить каждый элемент в отдельный цвет).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$), где $$$n$$$ обозначает длину последовательности.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). Числа в последовательности могут повторяться.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное количество цветов, которое нужно, чтобы покрасить все элементы корректным образом.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 10 2 3 5 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 100 100 100 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 7 6 5 4 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно покрасить элементы в $$$3$$$ цвета следующим образом:</p><ul> <li> покрасить в первый цвет элементы: $$$a_1=10$$$ и $$$a_4=5$$$, </li><li> покрасить во второй цвет элементы: $$$a_3=3$$$, </li><li> покрасить в третий цвет элементы: $$$a_2=2$$$, $$$a_5=4$$$ и $$$a_6=2$$$. </li></ul><p>Во втором примере можно использовать один цвет на все элементы.</p><p>В третьем примере можно покрасить элементы в $$$4$$$ цвета следующим образом:</p><ul> <li> покрасить в первый цвет элементы: $$$a_4=4$$$, $$$a_6=2$$$ и $$$a_7=2$$$, </li><li> покрасить во второй цвет элементы: $$$a_2=6$$$, $$$a_5=3$$$ и $$$a_8=3$$$, </li><li> покрасить в третий цвет элемент $$$a_3=5$$$, </li><li> покрасить в четвёртый цвет элемент $$$a_1=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="c888abc6792ea4c0a3c0901daee29622"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='c888abc6792ea4c0a3c0901daee29622'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='c888abc6792ea4c0a3c0901daee29622'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='c888abc6792ea4c0a3c0901daee29622'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='c888abc6792ea4c0a3c0901daee29622'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411977"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c888abc6792ea4c0a3c0901daee29622'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411977"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d3adcd8a2b59e3c539fc13d93d46bb270f4cadd1"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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_1, a_2, \dots, a_n$$$. Вам нужно раскрасить элементы, так чтобы: </p><ul> <li> Если мы рассмотрим произвольный цвет, то все элементы этого цвета должны делиться на минимальный элемент этого цвета. </li><li> Количество использованных цветов было бы минимально возможным. </li></ul><p>Например, можно покрасить элементы $$$[40, 10, 60]$$$ в один цвет, так как они все делятся на $$$10$$$. Каждый из цветов можно использовать произвольное количество раз (в частности, разрешается использовать любой цвет ровно один раз). Элементы, покрашенные в один цвет, не обязаны идти подряд.</p><p>Например, если $$$a=[6, 2, 3, 4, 12]$$$, то нужно использовать два цвета: можно покрасить $$$6$$$, $$$3$$$, $$$12$$$ в первый цвет ($$$6$$$, $$$3$$$ и $$$12$$$ делятся на $$$3$$$), а $$$2$$$ и $$$4$$$ во второй цвет ($$$2$$$ и $$$4$$$ делятся на $$$2$$$). Например, если $$$a=[10, 7, 15]$$$, то нужно $$$3$$$ цвета (следует покрасить каждый элемент в отдельный цвет).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$), где $$$n$$$ обозначает длину последовательности.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 100$$$). Числа в последовательности могут повторяться.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите минимальное количество цветов, которое нужно, чтобы покрасить все элементы корректным образом.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 10 2 3 5 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 100 100 100 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 7 6 5 4 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно покрасить элементы в $$$3$$$ цвета следующим образом:</p><ul> <li> покрасить в первый цвет элементы: $$$a_1=10$$$ и $$$a_4=5$$$, </li><li> покрасить во второй цвет элементы: $$$a_3=3$$$, </li><li> покрасить в третий цвет элементы: $$$a_2=2$$$, $$$a_5=4$$$ и $$$a_6=2$$$. </li></ul><p>Во втором примере можно использовать один цвет на все элементы.</p><p>В третьем примере можно покрасить элементы в $$$4$$$ цвета следующим образом:</p><ul> <li> покрасить в первый цвет элементы: $$$a_4=4$$$, $$$a_6=2$$$ и $$$a_7=2$$$, </li><li> покрасить во второй цвет элементы: $$$a_2=6$$$, $$$a_5=3$$$ и $$$a_8=3$$$, </li><li> покрасить в третий цвет элемент $$$a_3=5$$$, </li><li> покрасить в четвёртый цвет элемент $$$a_1=7$$$. </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 10:43: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:'812483745e127c17',t:'MTY5NjY2NDYxMC4xNTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*800"]
1209B
1209
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$$$ ламп, каждая из которых периодически моргает.</p><p>После того как Коала взглянул на лампы, он заметил, у каждой лампы есть два параметра $$$a_i$$$ и $$$b_i$$$. Лампа с параметрами $$$a_i$$$ и $$$b_i$$$ переключается (т.е. переходит из включённого состояния в выключенное или наоборот) каждую $$$a_i$$$-ю секунду начиная с $$$b_i$$$-й. Иначе говоря, она переключается (меняет своё состояние) в моменты $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \cdot a_i$$$ и так далее.</p><p>Вы знаете для каждой лампы, включена она изначально или нет, а также соответствующие параметры $$$a_i$$$ и $$$b_i$$$. Коала интересуется, чему будет равно наибольшее число ламп, которые будут одновременно включены. Вам нужно это выяснить.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/5b8ced351fc35747fda01b8c4aba8716b071979e.png" style="max-width: 100.0%;max-height: 100.0%;" width="643px"/> <span class="tex-font-size-small">Так выглядит состояние ламп в первом примере.</span> </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — число ламп.</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, $$$i$$$-й символ строки равен «<span class="tex-font-style-tt">1</span>», если $$$i$$$-я лампа изначально включена. Иначе $$$i$$$-й символ равен «<span class="tex-font-style-tt">0</span>».</p><p>$$$i$$$-я из следующих $$$n$$$ строк содержит два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le 5$$$) — параметры $$$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 101 3 3 3 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1111 3 4 5 2 3 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 011100 5 3 5 5 2 4 3 5 4 2 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере состояния ламп изображены на картинке выше. Наибольшее число одновременно включённых ламп равно $$$2$$$ (например в момент $$$2$$$).</p><p>Во втором примере все лампы изначально включены. Значит ответ равен $$$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="7772bbd76ac39b5e5c2c234a79a80af6"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='7772bbd76ac39b5e5c2c234a79a80af6'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='7772bbd76ac39b5e5c2c234a79a80af6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='7772bbd76ac39b5e5c2c234a79a80af6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='7772bbd76ac39b5e5c2c234a79a80af6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411978"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7772bbd76ac39b5e5c2c234a79a80af6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411978"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6cfa857a73ab234ebd1427061e844f08f87a5478"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ ламп, каждая из которых периодически моргает.</p><p>После того как Коала взглянул на лампы, он заметил, у каждой лампы есть два параметра $$$a_i$$$ и $$$b_i$$$. Лампа с параметрами $$$a_i$$$ и $$$b_i$$$ переключается (т.е. переходит из включённого состояния в выключенное или наоборот) каждую $$$a_i$$$-ю секунду начиная с $$$b_i$$$-й. Иначе говоря, она переключается (меняет своё состояние) в моменты $$$b_i$$$, $$$b_i + a_i$$$, $$$b_i + 2 \cdot a_i$$$ и так далее.</p><p>Вы знаете для каждой лампы, включена она изначально или нет, а также соответствующие параметры $$$a_i$$$ и $$$b_i$$$. Коала интересуется, чему будет равно наибольшее число ламп, которые будут одновременно включены. Вам нужно это выяснить.</p><center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/5b8ced351fc35747fda01b8c4aba8716b071979e.png" style="max-width: 100.0%;max-height: 100.0%;" width="643px" /> <span class="tex-font-size-small">Так выглядит состояние ламп в первом примере.</span> </center></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — число ламп.</p><p>Следующая строка содержит строку $$$s$$$ длины $$$n$$$, $$$i$$$-й символ строки равен «<span class="tex-font-style-tt">1</span>», если $$$i$$$-я лампа изначально включена. Иначе $$$i$$$-й символ равен «<span class="tex-font-style-tt">0</span>».</p><p>$$$i$$$-я из следующих $$$n$$$ строк содержит два целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le 5$$$) — параметры $$$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 101 3 3 3 2 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1111 3 4 5 2 3 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 011100 5 3 5 5 2 4 3 5 4 2 1 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 6 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере состояния ламп изображены на картинке выше. Наибольшее число одновременно включённых ламп равно $$$2$$$ (например в момент $$$2$$$).</p><p>Во втором примере все лампы изначально включены. Значит ответ равен $$$4$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'8124837d2e9a3a83',t:'MTY5NjY2NDYxMS41MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\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", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"]
1209C
1209
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$$$ цифр $$$d_1d_2 \dots d_{n}$$$. Вам нужно раскрасить все цифры в два цвета таким образом, чтобы:</p><ul> <li> каждая цифра была покрашена либо в цвет $$$1$$$, либо в цвет $$$2$$$; </li><li> если выписать подряд слева направо все цифры покрашенные в цвет $$$1$$$, а затем следом все цифры, покрашенные в цвет $$$2$$$, то полученная последовательность из $$$n$$$ цифр будет неубывающей (то есть каждая следующая цифра будет больше или равна предыдущей цифры). </li></ul><p>Например, для последовательности цифр $$$d=914$$$ единственная корректная раскраска имеет вид $$$211$$$ (в цвет $$$1$$$ покрашены две последние цифры, в цвет $$$2$$$ покрашена первая цифра). Обратите внимание, что $$$122$$$ не соответствует требованиям (результат выписывания $$$9$$$ и следом $$$14$$$ не является неубывающей последовательностью).</p><p>Допустимо, что какой-либо из двух цветов не используется вообще. Цифры, покрашенные в один цвет, не обязаны располагаться в последовательности подряд.</p><p>Найдите любой из возможных способов раскрасить заданную последовательность цифр требуемым способом или определите, что это невозможно сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных в тесте.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — длина заданной последовательности цифр.</p><p>Следующая строка содержит последовательность из $$$n$$$ цифр $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). Цифры записаны подряд без пробелов или каких-либо других разделителей. Последовательность может начинаться с <span class="tex-font-style-tt">0</span>.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк — ответы на каждый из наборов входных данных в тесте.</p><p>В случае существования решения для набора соответствующая строка вывода должна содержать любую из допустимых раскрасок, записанную в виде строки из $$$n$$$ цифр $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), где $$$t_i$$$ — это цвет, в который покрашена $$$i$$$-я цифра. Если допустимых решений несколько, выведите любую из них.</p><p>Если решения не существует, то в соответствующая строка вывода должна содержать единственный символ «<span class="tex-font-style-tt">-</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 12 040425524644 1 0 9 123456789 2 98 3 987 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 121212211211 1 222222222 21 - </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе $$$d=040425524644$$$. Вывод $$$t=121212211211$$$ является корректным, так как последовательность $$$0022444$$$ (покрашена в $$$1$$$), сконкатенированная с $$$44556$$$ (покрашена в $$$2$$$), равна последовательности $$$002244444556$$$, которая является результатом сортировки всех заданных $$$n$$$ цифр.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="812547bedd1e3ecccb93647a2cdc4dfb"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='812547bedd1e3ecccb93647a2cdc4dfb'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='812547bedd1e3ecccb93647a2cdc4dfb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='812547bedd1e3ecccb93647a2cdc4dfb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='812547bedd1e3ecccb93647a2cdc4dfb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411979"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='812547bedd1e3ecccb93647a2cdc4dfb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411979"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_66316fe1f806a4e8e1385108e6379873aa4f9988"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ цифр $$$d_1d_2 \dots d_{n}$$$. Вам нужно раскрасить все цифры в два цвета таким образом, чтобы:</p><ul> <li> каждая цифра была покрашена либо в цвет $$$1$$$, либо в цвет $$$2$$$; </li><li> если выписать подряд слева направо все цифры покрашенные в цвет $$$1$$$, а затем следом все цифры, покрашенные в цвет $$$2$$$, то полученная последовательность из $$$n$$$ цифр будет неубывающей (то есть каждая следующая цифра будет больше или равна предыдущей цифры). </li></ul><p>Например, для последовательности цифр $$$d=914$$$ единственная корректная раскраска имеет вид $$$211$$$ (в цвет $$$1$$$ покрашены две последние цифры, в цвет $$$2$$$ покрашена первая цифра). Обратите внимание, что $$$122$$$ не соответствует требованиям (результат выписывания $$$9$$$ и следом $$$14$$$ не является неубывающей последовательностью).</p><p>Допустимо, что какой-либо из двух цветов не используется вообще. Цифры, покрашенные в один цвет, не обязаны располагаться в последовательности подряд.</p><p>Найдите любой из возможных способов раскрасить заданную последовательность цифр требуемым способом или определите, что это невозможно сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных в тесте.</p><p>Первая строка каждого набора входных данных содержит целое число $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) — длина заданной последовательности цифр.</p><p>Следующая строка содержит последовательность из $$$n$$$ цифр $$$d_1d_2 \dots d_{n}$$$ ($$$0 \le d_i \le 9$$$). Цифры записаны подряд без пробелов или каких-либо других разделителей. Последовательность может начинаться с <span class="tex-font-style-tt">0</span>.</p><p>Гарантируется, что сумма значений $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$2\cdot10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ строк — ответы на каждый из наборов входных данных в тесте.</p><p>В случае существования решения для набора соответствующая строка вывода должна содержать любую из допустимых раскрасок, записанную в виде строки из $$$n$$$ цифр $$$t_1t_2 \dots t_n$$$ ($$$1 \le t_i \le 2$$$), где $$$t_i$$$ — это цвет, в который покрашена $$$i$$$-я цифра. Если допустимых решений несколько, выведите любую из них.</p><p>Если решения не существует, то в соответствующая строка вывода должна содержать единственный символ «<span class="tex-font-style-tt">-</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 12 040425524644 1 0 9 123456789 2 98 3 987 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 121212211211 1 222222222 21 - </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе $$$d=040425524644$$$. Вывод $$$t=121212211211$$$ является корректным, так как последовательность $$$0022444$$$ (покрашена в $$$1$$$), сконкатенированная с $$$44556$$$ (покрашена в $$$2$$$), равна последовательности $$$002244444556$$$, которая является результатом сортировки всех заданных $$$n$$$ цифр.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'81248385aab89d51',t:'MTY5NjY2NDYxMi44NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1500"]
1209D
1209
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>Есть $$$n$$$ разных видов закусок, пронумерованных числами $$$1, 2, \ldots, n$$$. У Бесси есть $$$n$$$ закусок, по одной закуске каждого вида. У каждого гостя есть ровно два любимых вида закусок. Процесс перекуса будет происходить следующим образом:</p><ul> <li> Сначала Бесси упорядочит всех гостей в каком-то порядке. </li><li> Затем, в этом порядке гости будут по одному подходить к закускам. </li><li> Каждый гость будет в свой ход съедать все оставшиеся закуски любимых типов. В случае, если не осталось ни одной закуски любимых типов, то гость уйдёт очень грустным. </li></ul> <p>Помогите Бесси минимизировать число грустных гостей, упорядочив гостей правильным образом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le 10^5$$$) — количество закусок и количество гостей.</p><p>$$$i$$$-я из следующих $$$k$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — любимые виды закусок для $$$i$$$-го гостя.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное возможное количество грустных гостей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 4 3 1 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 5 2 3 2 1 3 4 6 5 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Бесси может упорядочить гостей следующим образом: $$$3, 1, 2, 4$$$. Гость $$$3$$$ пойдёт первым и съест закуски $$$1$$$ и $$$4$$$. Затем идёт гость $$$1$$$ и съедает закуску $$$2$$$, так как закуска $$$1$$$ уже съедена. Затем приходит гость $$$2$$$ и съедает только закуску $$$3$$$. Так как все закуски уже съедены, то гость $$$4$$$ будет грустным.</p><p>Во втором примере можно упорядочить гостей как $$$2, 1, 3, 5, 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="9abcd5437aa18e51c4950ce5920b0134"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='9abcd5437aa18e51c4950ce5920b0134'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='9abcd5437aa18e51c4950ce5920b0134'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='9abcd5437aa18e51c4950ce5920b0134'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='9abcd5437aa18e51c4950ce5920b0134'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411980"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9abcd5437aa18e51c4950ce5920b0134'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411980"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_982bf81e8ce6e0e1b7b1b24b8559c710b74e135e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Есть $$$n$$$ разных видов закусок, пронумерованных числами $$$1, 2, \ldots, n$$$. У Бесси есть $$$n$$$ закусок, по одной закуске каждого вида. У каждого гостя есть ровно два любимых вида закусок. Процесс перекуса будет происходить следующим образом:</p><ul> <li> Сначала Бесси упорядочит всех гостей в каком-то порядке. </li><li> Затем, в этом порядке гости будут по одному подходить к закускам. </li><li> Каждый гость будет в свой ход съедать все оставшиеся закуски любимых типов. В случае, если не осталось ни одной закуски любимых типов, то гость уйдёт очень грустным. </li></ul> <p>Помогите Бесси минимизировать число грустных гостей, упорядочив гостей правильным образом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^5$$$, $$$1 \le k \le 10^5$$$) — количество закусок и количество гостей.</p><p>$$$i$$$-я из следующих $$$k$$$ строк содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — любимые виды закусок для $$$i$$$-го гостя.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное возможное количество грустных гостей.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 4 1 2 4 3 1 4 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 5 2 3 2 1 3 4 6 5 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Бесси может упорядочить гостей следующим образом: $$$3, 1, 2, 4$$$. Гость $$$3$$$ пойдёт первым и съест закуски $$$1$$$ и $$$4$$$. Затем идёт гость $$$1$$$ и съедает закуску $$$2$$$, так как закуска $$$1$$$ уже съедена. Затем приходит гость $$$2$$$ и съедает только закуску $$$3$$$. Так как все закуски уже съедены, то гость $$$4$$$ будет грустным.</p><p>Во втором примере можно упорядочить гостей как $$$2, 1, 3, 5, 4$$$. Тогда все гости будут удовлетворены.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'8124838e1f68005d',t:'MTY5NjY2NDYxNC4xNzUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "*1700"]
1209E1
1209
E1
ru
E1. Вращая столбцы (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Вращая столбцы (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более лёгкая версия следующей задачи, отличающаяся от неё только ограничениями</span>. </p><p>Вам дана прямоугольная матрица $$$a$$$ размером $$$n \times m$$$. За один ход вы можете выбрать произвольный столбец и циклически сдвинуть все элементы в этом столбце. Вы можете выполнять эту операцию произвольное (ноль или более) количество раз. Вы можете применять эту операцию для одного столбца произвольное количество раз.</p><p>После того, как вы закончили, вы вычисляете для каждой строки наибольший элемент в ней. Предположим, для $$$i$$$-й строки он равен $$$r_i$$$. Чему равно наибольшее значение $$$r_1+r_2+\ldots+r_n$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 40$$$), количество наборов входных данных в тесте.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 4$$$, $$$1 \le m \le 100$$$) — число строк и число столбцов в матрице $$$a$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ чисел — элементы матрицы $$$a$$$ ($$$1 \le a_{i, j} \le 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> 2 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе можно сдвинуть третий столбец вниз на один, тогда будет $$$r_1 = 5$$$ и $$$r_2 = 7$$$.</p><p>Во втором тестовом наборе можно ничего не делать, тогда будет $$$r_1 = r_2 = 10$$$ и $$$r_3 = 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="a9e618d97d4ec407714db0d4771cb818"/> <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="Задача - E1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='a9e618d97d4ec407714db0d4771cb818'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%2Fproblem%2FE1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='a9e618d97d4ec407714db0d4771cb818'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='a9e618d97d4ec407714db0d4771cb818'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='a9e618d97d4ec407714db0d4771cb818'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411981"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a9e618d97d4ec407714db0d4771cb818'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411981"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="E1" data-uuid="ps_80a6d28d1e40a137a1278443ff8cfe3fc735d8f2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">E1. Вращая столбцы (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более лёгкая версия следующей задачи, отличающаяся от неё только ограничениями</span>. </p><p>Вам дана прямоугольная матрица $$$a$$$ размером $$$n \times m$$$. За один ход вы можете выбрать произвольный столбец и циклически сдвинуть все элементы в этом столбце. Вы можете выполнять эту операцию произвольное (ноль или более) количество раз. Вы можете применять эту операцию для одного столбца произвольное количество раз.</p><p>После того, как вы закончили, вы вычисляете для каждой строки наибольший элемент в ней. Предположим, для $$$i$$$-й строки он равен $$$r_i$$$. Чему равно наибольшее значение $$$r_1+r_2+\ldots+r_n$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 40$$$), количество наборов входных данных в тесте.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 4$$$, $$$1 \le m \le 100$$$) — число строк и число столбцов в матрице $$$a$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ чисел — элементы матрицы $$$a$$$ ($$$1 \le a_{i, j} \le 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> 2 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 29 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе можно сдвинуть третий столбец вниз на один, тогда будет $$$r_1 = 5$$$ и $$$r_2 = 7$$$.</p><p>Во втором тестовом наборе можно ничего не делать, тогда будет $$$r_1 = r_2 = 10$$$ и $$$r_3 = 9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483964e684d90',t:'MTY5NjY2NDYxNS41MDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2000"]
1209E2
1209
E2
ru
E2. Вращая столбцы (усложнённая версия)
<div class="problem-statement"><div class="header"><div class="title">E2. Вращая столбцы (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия задачи, отличающаяся более высокими ограничениями</span>.</p><p>Вам дана прямоугольная матрица $$$a$$$ размером $$$n \times m$$$. За один ход вы можете выбрать произвольный столбец и циклически сдвинуть все элементы в этом столбце. Вы можете выполнять эту операцию произвольное (ноль или более) количество раз. Вы можете применять эту операцию для одного столбца произвольное количество раз.</p><p>После того, как вы закончили, вы вычисляете для каждой строки наибольший элемент в ней. Предположим, для $$$i$$$-й строки он равен $$$r_i$$$. Чему равно наибольшее значение $$$r_1+r_2+\ldots+r_n$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 40$$$), количество наборов входных данных в тесте.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 12$$$, $$$1 \le m \le 2000$$$) — число строк и число столбцов в матрице $$$a$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ чисел — элементы матрицы $$$a$$$ ($$$1 \le a_{i, j} \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел: ответы на все наборы входных данных, в порядке, в котором они заданы в тесте.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 3 3 9 9 9 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 29 27 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе можно сдвинуть третий столбец вниз на один, тогда будет $$$r_1 = 5$$$ и $$$r_2 = 7$$$.</p><p>Во втором тестовом наборе можно ничего не делать, тогда будет $$$r_1 = r_2 = 10$$$ и $$$r_3 = 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="7a303c712c59c325b7788f3220e3c727"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='7a303c712c59c325b7788f3220e3c727'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='7a303c712c59c325b7788f3220e3c727'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='7a303c712c59c325b7788f3220e3c727'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='7a303c712c59c325b7788f3220e3c727'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411982"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7a303c712c59c325b7788f3220e3c727'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411982"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_20e0a44da52d7cddd7e754a1a2ee43e6ffcf210c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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-it">Это сложная версия задачи, отличающаяся более высокими ограничениями</span>.</p><p>Вам дана прямоугольная матрица $$$a$$$ размером $$$n \times m$$$. За один ход вы можете выбрать произвольный столбец и циклически сдвинуть все элементы в этом столбце. Вы можете выполнять эту операцию произвольное (ноль или более) количество раз. Вы можете применять эту операцию для одного столбца произвольное количество раз.</p><p>После того, как вы закончили, вы вычисляете для каждой строки наибольший элемент в ней. Предположим, для $$$i$$$-й строки он равен $$$r_i$$$. Чему равно наибольшее значение $$$r_1+r_2+\ldots+r_n$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$t$$$ ($$$1 \le t \le 40$$$), количество наборов входных данных в тесте.</p><p>Первая строка каждого набора входных данных содержит целые числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 12$$$, $$$1 \le m \le 2000$$$) — число строк и число столбцов в матрице $$$a$$$.</p><p>Каждая из следующих $$$n$$$ строк содержит $$$m$$$ чисел — элементы матрицы $$$a$$$ ($$$1 \le a_{i, j} \le 10^5$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел: ответы на все наборы входных данных, в порядке, в котором они заданы в тесте.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 2 3 2 5 7 4 2 4 3 6 4 1 5 2 10 4 8 6 6 4 9 10 5 4 9 5 8 7 3 3 9 9 9 1 1 1 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 29 27 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом наборе можно сдвинуть третий столбец вниз на один, тогда будет $$$r_1 = 5$$$ и $$$r_2 = 7$$$.</p><p>Во втором тестовом наборе можно ничего не делать, тогда будет $$$r_1 = r_2 = 10$$$ и $$$r_3 = 9$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'8124839e9f337b3f',t:'MTY5NjY2NDYxNi44OTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2500"]
1209F
1209
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>Страна коал состоит из $$$n$$$ городов и $$$m$$$ двусторонних дорог, их соединяющих. Дороги пронумерованы от $$$1$$$ до $$$m$$$ в порядке входных данных. Гарантируется, что можно добраться от каждого города до любого другого города.</p><p>Коала начинает путешествие из города $$$1$$$. Каждый раз, когда он проходит по дороге, он записывает её номер в блокнот. Он не делает пробелов между числами, так что все записи склеятся в одно большое число.</p><p>Перед тем как отправится в свой путь, Коала интересуется какое число может получится в блокноте в зависимости от конечного пункта. Для каждого возможного конечного пункта выясните, какое наименьшее число может для него получиться?</p><p>Так как эти числа могут быть достаточно большими, вычислите их по модулю $$$10^9+7$$$. Обратите внимание, что нужно вычислить остаток минимального возможного числа, <span class="tex-font-style-bf">не</span> минимально возможный остаток. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$) — количество городов и количество дорог соответственно.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит целые числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), обозначающие двустороннюю дорогу между $$$x_i$$$ и $$$y_i$$$.</p><p>Гарантируется, что для каждой пары городов есть не более одной дороги их соединяющей, и что можно добраться из каждого города до любого другого.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n - 1$$$ целое число — ответ для каждого города за исключением первого.</p><p>$$$i$$$-е число должно быть равно наименьшему числу, которое получилось бы для конечной точки $$$i+1$$$. Так как это число может быть достаточно большим, выведите его остаток по модулю $$$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> 11 10 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 123 1234 12345 123456 1234567 12345678 123456789 345678826 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 19 1 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 2 10 3 11 11 12 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 13 14 15 16 17 18 19 1210 121011 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 14 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 1 3 1 4 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 13 134 1345 13456 1498 149 14 1410 141011 </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="d872fa0b68bbc20f3207136d764a17a8"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='d872fa0b68bbc20f3207136d764a17a8'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='d872fa0b68bbc20f3207136d764a17a8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='d872fa0b68bbc20f3207136d764a17a8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Кучи, деревья отрезков, деревья поиска и др."> структуры данных </span> </div> <div class="roundbox borderTopRound 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='d872fa0b68bbc20f3207136d764a17a8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411983"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d872fa0b68bbc20f3207136d764a17a8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411983"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8e528e882b47cbb6be67f2a5d0490cdf405bc6dc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Страна коал состоит из $$$n$$$ городов и $$$m$$$ двусторонних дорог, их соединяющих. Дороги пронумерованы от $$$1$$$ до $$$m$$$ в порядке входных данных. Гарантируется, что можно добраться от каждого города до любого другого города.</p><p>Коала начинает путешествие из города $$$1$$$. Каждый раз, когда он проходит по дороге, он записывает её номер в блокнот. Он не делает пробелов между числами, так что все записи склеятся в одно большое число.</p><p>Перед тем как отправится в свой путь, Коала интересуется какое число может получится в блокноте в зависимости от конечного пункта. Для каждого возможного конечного пункта выясните, какое наименьшее число может для него получиться?</p><p>Так как эти числа могут быть достаточно большими, вычислите их по модулю $$$10^9+7$$$. Обратите внимание, что нужно вычислить остаток минимального возможного числа, <span class="tex-font-style-bf">не</span> минимально возможный остаток. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 10^5, n - 1 \le m \le 10^5$$$) — количество городов и количество дорог соответственно.</p><p>$$$i$$$-я из следующих $$$m$$$ строк содержит целые числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$), обозначающие двустороннюю дорогу между $$$x_i$$$ и $$$y_i$$$.</p><p>Гарантируется, что для каждой пары городов есть не более одной дороги их соединяющей, и что можно добраться из каждого города до любого другого.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n - 1$$$ целое число — ответ для каждого города за исключением первого.</p><p>$$$i$$$-е число должно быть равно наименьшему числу, которое получилось бы для конечной точки $$$i+1$$$. Так как это число может быть достаточно большим, выведите его остаток по модулю $$$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> 11 10 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 123 1234 12345 123456 1234567 12345678 123456789 345678826 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 19 1 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 2 10 3 11 11 12 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 13 14 15 16 17 18 19 1210 121011 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 14 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12 1 3 1 4 1 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 12 13 134 1345 13456 1498 149 14 1410 141011 </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 10:43:38</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:'812483a758a47b63',t:'MTY5NjY2NDYxOC40MzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438 \u043d\u0430 \u0433\u0440\u0430\u0444\u0430\u0445", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u0440\u0430\u0442\u0447\u0430\u0439\u0448\u0438\u0435 \u043f\u0443\u0442\u0438", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
1209G1
1209
G1
ru
G1. На блоки (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">G1. На блоки (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия следующей задачи. В данной версии $$$q = 0$$$</span>.</p><p>Последовательность чисел называется <span class="tex-font-style-it">хорошей</span>, если элементы разбиты на блоки как в $$$[3, 3, 3, 4, 1, 1]$$$. Формально, если два элемента равны, то все элементы между ними должны быть тоже равны тому же значению.</p><p>Определим <span class="tex-font-style-it">сложность</span> последовательности как минимальное число элементов, которое нужно поменять, чтобы получить хорошую последовательность. Однако, если вы заменяете хотя бы один $$$x$$$ на какое-то значение $$$y$$$, нужно заменить все остальные значения $$$x$$$ на $$$y$$$ тоже. Например, для $$$[3, 3, 1, 3, 2, 1, 2]$$$ не разрешается поменять первую $$$1$$$ на $$$3$$$, а вторую $$$1$$$ на $$$2$$$. Вы можете или не заменять $$$1$$$ совсем, или заменить их все на что-то одно.</p><p>Вам дана последовательность целых чисел $$$a_1, a_2, \ldots, a_n$$$ и $$$q$$$ изменений.</p><p>Каждое изменение имеет вид «$$$i$$$ $$$x$$$» — заменить $$$a_i$$$ на $$$x$$$.</p><p>Выведите сложность изначальной последовательности и последовательности после каждого изменения. Обратите внимание, что изменения не независимы (изменение сохраняется на будущее).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 200\,000$$$, $$$q = 0$$$) — длина последовательности и число изменений.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\,000$$$) — изначальную последовательность.</p><p>Каждая из следующих $$$q$$$ строк содержит целые числа $$$i_t$$$ и $$$x_t$$$ ($$$1 \le i_t \le n$$$, $$$1 \le x_t \le 200\,000$$$) — позицию и новое значение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+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 0 3 7 3 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 0 1 2 1 2 3 1 1 1 50 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 0 6 6 3 3 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 3 3 1 3 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="82a1681314a0bfbdc677cde3b080e5ed"/> <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="Задача - G1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G1 - Codeforces</title> <meta 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='82a1681314a0bfbdc677cde3b080e5ed'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%2Fproblem%2FG1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='82a1681314a0bfbdc677cde3b080e5ed'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='82a1681314a0bfbdc677cde3b080e5ed'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='82a1681314a0bfbdc677cde3b080e5ed'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411984"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='82a1681314a0bfbdc677cde3b080e5ed'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411984"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="G1" data-uuid="ps_84d1938b1cb257d17c9ec42e8cf34111f229e009"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">G1. На блоки (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это более простая версия следующей задачи. В данной версии $$$q = 0$$$</span>.</p><p>Последовательность чисел называется <span class="tex-font-style-it">хорошей</span>, если элементы разбиты на блоки как в $$$[3, 3, 3, 4, 1, 1]$$$. Формально, если два элемента равны, то все элементы между ними должны быть тоже равны тому же значению.</p><p>Определим <span class="tex-font-style-it">сложность</span> последовательности как минимальное число элементов, которое нужно поменять, чтобы получить хорошую последовательность. Однако, если вы заменяете хотя бы один $$$x$$$ на какое-то значение $$$y$$$, нужно заменить все остальные значения $$$x$$$ на $$$y$$$ тоже. Например, для $$$[3, 3, 1, 3, 2, 1, 2]$$$ не разрешается поменять первую $$$1$$$ на $$$3$$$, а вторую $$$1$$$ на $$$2$$$. Вы можете или не заменять $$$1$$$ совсем, или заменить их все на что-то одно.</p><p>Вам дана последовательность целых чисел $$$a_1, a_2, \ldots, a_n$$$ и $$$q$$$ изменений.</p><p>Каждое изменение имеет вид «$$$i$$$ $$$x$$$» — заменить $$$a_i$$$ на $$$x$$$.</p><p>Выведите сложность изначальной последовательности и последовательности после каждого изменения. Обратите внимание, что изменения не независимы (изменение сохраняется на будущее).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 200\,000$$$, $$$q = 0$$$) — длина последовательности и число изменений.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\,000$$$) — изначальную последовательность.</p><p>Каждая из следующих $$$q$$$ строк содержит целые числа $$$i_t$$$ и $$$x_t$$$ ($$$1 \le i_t \le n$$$, $$$1 \le x_t \le 200\,000$$$) — позицию и новое значение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+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 0 3 7 3 7 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 0 1 2 1 2 3 1 1 1 50 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 0 6 6 3 3 4 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 3 3 1 3 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").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 10:43: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:'812483b0ec551634',t:'MTY5NjY2NDYxOS44MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0432\u0430 \u0443\u043a\u0430\u0437\u0430\u0442\u0435\u043b\u044f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2000"]
1209G2
1209
G2
ru
G2. На блоки (усложнённая версия)
<div class="problem-statement"><div class="header"><div class="title">G2. На блоки (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия задачи. В данной версии $$$q \le 200\,000$$$.</span></p><p>Последовательность чисел называется <span class="tex-font-style-it">хорошей</span>, если элементы разбиты на блоки как в $$$[3, 3, 3, 4, 1, 1]$$$. Формально, если два элемента равны, то все элементы между ними должны быть тоже равны тому же значению.</p><p>Определим <span class="tex-font-style-it">сложность</span> последовательности как минимальное число элементов, которое нужно поменять, чтобы получить хорошую последовательность. Однако, если вы заменяете хотя бы один $$$x$$$ на какое-то значение $$$y$$$, нужно заменить все остальные значения $$$x$$$ на $$$y$$$ тоже. Например, для $$$[3, 3, 1, 3, 2, 1, 2]$$$ не разрешается поменять первую $$$1$$$ на $$$3$$$, а вторую $$$1$$$ на $$$2$$$. Вы можете или не заменять $$$1$$$ совсем, или заменить их все на что-то одно.</p><p>Вам дана последовательность целых чисел $$$a_1, a_2, \ldots, a_n$$$ и $$$q$$$ изменений.</p><p>Каждое изменение имеет вид «$$$i$$$ $$$x$$$» — заменить $$$a_i$$$ на $$$x$$$.</p><p>Выведите сложность изначальной последовательности и последовательности после каждого изменения. Обратите внимание, что изменения не независимы (изменение сохраняется на будущее).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le q \le 200\,000$$$) — длина последовательности и число изменений.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\,000$$$) — изначальную последовательность.</p><p>Каждая из следующих $$$q$$$ строк содержит целые числа $$$i_t$$$ и $$$x_t$$$ ($$$1 \le i_t \le n$$$, $$$1 \le x_t \le 200\,000$$$) — позицию и новое значение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+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 6 1 2 1 2 1 2 1 4 1 5 3 2 3 4 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 0 2 3 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="6d82c4a6fefa7ea6daa8bacada755485"/> <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="Задача - G2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - G2 - Codeforces</title> <meta 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='6d82c4a6fefa7ea6daa8bacada755485'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%2Fproblem%2FG2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='6d82c4a6fefa7ea6daa8bacada755485'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='6d82c4a6fefa7ea6daa8bacada755485'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='6d82c4a6fefa7ea6daa8bacada755485'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411985"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6d82c4a6fefa7ea6daa8bacada755485'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411985"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="G2" data-uuid="ps_6a8a92b7c113136b9baa3023577dcbeb2aafcf95"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">G2. На блоки (усложнённая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-it">Это сложная версия задачи. В данной версии $$$q \le 200\,000$$$.</span></p><p>Последовательность чисел называется <span class="tex-font-style-it">хорошей</span>, если элементы разбиты на блоки как в $$$[3, 3, 3, 4, 1, 1]$$$. Формально, если два элемента равны, то все элементы между ними должны быть тоже равны тому же значению.</p><p>Определим <span class="tex-font-style-it">сложность</span> последовательности как минимальное число элементов, которое нужно поменять, чтобы получить хорошую последовательность. Однако, если вы заменяете хотя бы один $$$x$$$ на какое-то значение $$$y$$$, нужно заменить все остальные значения $$$x$$$ на $$$y$$$ тоже. Например, для $$$[3, 3, 1, 3, 2, 1, 2]$$$ не разрешается поменять первую $$$1$$$ на $$$3$$$, а вторую $$$1$$$ на $$$2$$$. Вы можете или не заменять $$$1$$$ совсем, или заменить их все на что-то одно.</p><p>Вам дана последовательность целых чисел $$$a_1, a_2, \ldots, a_n$$$ и $$$q$$$ изменений.</p><p>Каждое изменение имеет вид «$$$i$$$ $$$x$$$» — заменить $$$a_i$$$ на $$$x$$$.</p><p>Выведите сложность изначальной последовательности и последовательности после каждого изменения. Обратите внимание, что изменения не независимы (изменение сохраняется на будущее).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$q$$$ ($$$1 \le n \le 200\,000$$$, $$$0 \le q \le 200\,000$$$) — длина последовательности и число изменений.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 200\,000$$$) — изначальную последовательность.</p><p>Каждая из следующих $$$q$$$ строк содержит целые числа $$$i_t$$$ и $$$x_t$$$ ($$$1 \le i_t \le n$$$, $$$1 \le x_t \le 200\,000$$$) — позицию и новое значение.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q+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 6 1 2 1 2 1 2 1 4 1 5 3 2 3 4 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 0 0 2 3 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").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 10:43: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:'812483b98f12064b',t:'MTY5NjY2NDYyMS4yMDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"]
1209H
1209
H
ru
H. Траволаторы
<div class="problem-statement"><div class="header"><div class="title">H. Траволаторы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В аэропортах часто используются траволаторы, потому что они помогают проходить большие расстояния быстрее. Каждый траволатор имеет некоторую собственную скорость, которая увеличивает скорость, с которой вы идёте. Вы можете просто стоять на траволаторе (тогда вы будете двигаться со скоростью траволатора), либо вы можете ещё и идти, тогда ваша итоговая скорость будет равна сумме скорости, с который вы идёте, и скорости траволатора.</p><p>Лимак хочет добраться из точки $$$0$$$ в точку $$$L$$$, расположенные на одной прямой. Между ними есть $$$n$$$ дизъюнктных траволаторов. $$$i$$$-й из них описывается целыми числами $$$x_i$$$, $$$y_i$$$ и вещественным числом $$$s_i$$$. $$$i$$$-й траволатор начинается в $$$x_i$$$, заканчивается в $$$y_i$$$ и имеет скорость $$$s_i$$$.</p><p>Каждый траволатор расположен внутри отрезка $$$[0, L]$$$ и никакие два траволатора не имеют ненулевую длину пересечения. При этом траволаторы могут касаться.</p><p>Лимак хочет понять, как ему следует распределить свою энергию. Например, может быть оптимально стоять где-нибудь (или идти с низкой скоростью), чтобы сэкономить энергию и потом идти быстрее.</p><p>Изначально энергия Лимака равна $$$0$$$, и она никогда не должна падать ниже этого значения. В каждый момент он может идти со скоростью $$$v$$$ в диапазоне $$$[0, 2]$$$, и это будет стоить ему $$$v$$$ энергии. Также его энергия постоянно пополняется со скоростью $$$1$$$ единица энергии в секунду. Таким образом, если он идёт со скоростью $$$v$$$, его энергия растёт со скоростью $$$(1-v)$$$. Обратите внимание, что негативный рост означает убывание энергии.</p><p>В частности, Лимак может идти со скоростью $$$1$$$, и это никак не будет влиять на его уровень энергии, а если он будет идти со скорость $$$0.77$$$, то энергия будет расти на $$$0.23$$$.</p><p>Лимак может выбирать свою скорость произвольным образом (любое вещественное число в диапазоне $$$[0, 2]$$$) в каждый момент времени (в том числе в моменты, когда он находится в нецелых позициях). Всё происходит непрерывно (не дискретно).</p><p>За какое минимальное время Лимак сможет добраться из $$$0$$$ в $$$L$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$L$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le L \le 10^9$$$), число траволаторов и расстояние, которое нужно пройти.</p><p>Каждая из следующих $$$n$$$ строк содержит целые числа $$$x_i$$$, $$$y_i$$$ и вещественное число $$$s_i$$$ ($$$0 \le x_i &lt; y_i \le L$$$, $$$0.1 \le s_i \le 10.0$$$). Значение $$$s_i$$$ дано с не более, чем $$$9$$$ знаками после запятой.</p><p>Гарантируется, что никакие два траволатора не имеют пересечения ненулевой длины. Траволаторы перечислены слева направо. Иначе говоря, $$$y_i \le x_{i + 1}$$$ при $$$1 \le i \le n - 1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно вещественное число — минимальное время, которое нужно чтобы достичь $$$L$$$. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не будет превосходить $$$10^{-9}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 5 0 2 2.0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3.000000000000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 4 0.91 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3.808900523560 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1000 0 990 1.777777 995 996 1.123456789 996 1000 2.0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 361.568848429553 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка изображает первые два примера. В первом примере есть траволатор из $$$0$$$ в $$$2$$$ скорости $$$2.0$$$, а Лимак хочет попасть в точку $$$5$$$. Во втором примере есть траволатор из $$$2$$$ в $$$4$$$ скорости $$$0.91$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/17fbff67d5963ecf551eb5bb2e166242f24e7554.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>В первом примере, одна из оптимальных стратегий выглядит следующим образом.</p><ul> <li> Добраться из $$$0$$$ в $$$2$$$ просто стоя на траволаторе. Траволатор едет со скоростью $$$2$$$, значит понадобится всего $$$1$$$ секунда времени и энергия увеличится на $$$1$$$. </li><li> Добраться из $$$2$$$ в $$$4$$$ идя со скоростью $$$2$$$ в течении $$$1$$$ секунды. За эту $$$1$$$ секунду уровень энергии понизится до $$$0$$$. </li><li> Добраться из $$$4$$$ в $$$5$$$ идя со скоростью $$$1$$$. На это понадобится $$$1$$$ секунда и уровень энергии будет равен $$$0$$$ всё это время. </li></ul><p>Тем самым общее время равно $$$1 + 1 + 1 = 3$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="95a7182eb5ed23ad8a4babfcb2456b70"/> <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="46e593635b2d6e933ddb99364dec1331c6ad9519"/> <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='95a7182eb5ed23ad8a4babfcb2456b70'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1209%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='95a7182eb5ed23ad8a4babfcb2456b70'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1209">Codeforces Round 584 - Dasha Code Championship - отборочный раунд (рейтинговый, открыт для всех, Div. 1 + 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='95a7182eb5ed23ad8a4babfcb2456b70'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1209/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='95a7182eb5ed23ad8a4babfcb2456b70'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="411986"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='95a7182eb5ed23ad8a4babfcb2456b70'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="411986"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69764" title="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + div. 2)" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9332" resourceName="Codeforces Round #584 (Dasha Code Championship Elimination Round) (div. 1 + 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="https://codeforces.com/blog/entry/69791" title="69791" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9335" resourceName="69791" 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/1209">Задачи</a></li> <li><a href="/contest/1209/submit">Отослать</a></li> <li><a href="/contest/1209/my">Мои посылки</a></li> <li><a href="/contest/1209/status">Статус</a></li> <li><a href="/contest/1209/hacks">Взломы</a></li> <li><a href="/contest/1209/room/1">Комната</a></li> <li><a href="/contest/1209/standings">Положение</a></li> <li><a href="/contest/1209/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8039fc9870db23bb9b91bb0bba1229725ebfb04d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Траволаторы</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>В аэропортах часто используются траволаторы, потому что они помогают проходить большие расстояния быстрее. Каждый траволатор имеет некоторую собственную скорость, которая увеличивает скорость, с которой вы идёте. Вы можете просто стоять на траволаторе (тогда вы будете двигаться со скоростью траволатора), либо вы можете ещё и идти, тогда ваша итоговая скорость будет равна сумме скорости, с который вы идёте, и скорости траволатора.</p><p>Лимак хочет добраться из точки $$$0$$$ в точку $$$L$$$, расположенные на одной прямой. Между ними есть $$$n$$$ дизъюнктных траволаторов. $$$i$$$-й из них описывается целыми числами $$$x_i$$$, $$$y_i$$$ и вещественным числом $$$s_i$$$. $$$i$$$-й траволатор начинается в $$$x_i$$$, заканчивается в $$$y_i$$$ и имеет скорость $$$s_i$$$.</p><p>Каждый траволатор расположен внутри отрезка $$$[0, L]$$$ и никакие два траволатора не имеют ненулевую длину пересечения. При этом траволаторы могут касаться.</p><p>Лимак хочет понять, как ему следует распределить свою энергию. Например, может быть оптимально стоять где-нибудь (или идти с низкой скоростью), чтобы сэкономить энергию и потом идти быстрее.</p><p>Изначально энергия Лимака равна $$$0$$$, и она никогда не должна падать ниже этого значения. В каждый момент он может идти со скоростью $$$v$$$ в диапазоне $$$[0, 2]$$$, и это будет стоить ему $$$v$$$ энергии. Также его энергия постоянно пополняется со скоростью $$$1$$$ единица энергии в секунду. Таким образом, если он идёт со скоростью $$$v$$$, его энергия растёт со скоростью $$$(1-v)$$$. Обратите внимание, что негативный рост означает убывание энергии.</p><p>В частности, Лимак может идти со скоростью $$$1$$$, и это никак не будет влиять на его уровень энергии, а если он будет идти со скорость $$$0.77$$$, то энергия будет расти на $$$0.23$$$.</p><p>Лимак может выбирать свою скорость произвольным образом (любое вещественное число в диапазоне $$$[0, 2]$$$) в каждый момент времени (в том числе в моменты, когда он находится в нецелых позициях). Всё происходит непрерывно (не дискретно).</p><p>За какое минимальное время Лимак сможет добраться из $$$0$$$ в $$$L$$$?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целые числа $$$n$$$ и $$$L$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le L \le 10^9$$$), число траволаторов и расстояние, которое нужно пройти.</p><p>Каждая из следующих $$$n$$$ строк содержит целые числа $$$x_i$$$, $$$y_i$$$ и вещественное число $$$s_i$$$ ($$$0 \le x_i &lt; y_i \le L$$$, $$$0.1 \le s_i \le 10.0$$$). Значение $$$s_i$$$ дано с не более, чем $$$9$$$ знаками после запятой.</p><p>Гарантируется, что никакие два траволатора не имеют пересечения ненулевой длины. Траволаторы перечислены слева направо. Иначе говоря, $$$y_i \le x_{i + 1}$$$ при $$$1 \le i \le n - 1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно вещественное число — минимальное время, которое нужно чтобы достичь $$$L$$$. Ваш ответ будет считаться правильным, если его абсолютная или относительная ошибка не будет превосходить $$$10^{-9}$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 1 5 0 2 2.0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3.000000000000 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 5 2 4 0.91 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3.808900523560 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1000 0 990 1.777777 995 996 1.123456789 996 1000 2.0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 361.568848429553 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка изображает первые два примера. В первом примере есть траволатор из $$$0$$$ в $$$2$$$ скорости $$$2.0$$$, а Лимак хочет попасть в точку $$$5$$$. Во втором примере есть траволатор из $$$2$$$ в $$$4$$$ скорости $$$0.91$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/17fbff67d5963ecf551eb5bb2e166242f24e7554.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>В первом примере, одна из оптимальных стратегий выглядит следующим образом.</p><ul> <li> Добраться из $$$0$$$ в $$$2$$$ просто стоя на траволаторе. Траволатор едет со скоростью $$$2$$$, значит понадобится всего $$$1$$$ секунда времени и энергия увеличится на $$$1$$$. </li><li> Добраться из $$$2$$$ в $$$4$$$ идя со скоростью $$$2$$$ в течении $$$1$$$ секунды. За эту $$$1$$$ секунду уровень энергии понизится до $$$0$$$. </li><li> Добраться из $$$4$$$ в $$$5$$$ идя со скоростью $$$1$$$. На это понадобится $$$1$$$ секунда и уровень энергии будет равен $$$0$$$ всё это время. </li></ul><p>Тем самым общее время равно $$$1 + 1 + 1 = 3$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=H]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483c22ea79d6d',t:'MTY5NjY2NDYyMi41NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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.", "\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3300"]
1210A
1210
A
ru
A. Анади и домино
<div class="problem-statement"><div class="header"><div class="title">A. Анади и домино</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Анади есть комплект домино. Каждое домино разделено на две части, на каждой части нарисовано сколько-то точек. Для каждой такой пары $$$a$$$ и $$$b$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4ea43cc1e9994b7b1348985e20611bcb"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='4ea43cc1e9994b7b1348985e20611bcb'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='4ea43cc1e9994b7b1348985e20611bcb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='4ea43cc1e9994b7b1348985e20611bcb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='4ea43cc1e9994b7b1348985e20611bcb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417808"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4ea43cc1e9994b7b1348985e20611bcb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417808"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_23ee531cac3b9343ea6f085518ff016518e6693d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ и $$$b$$$, что $$$1 \leq a \leq b \leq 6$$$, есть ровно одно домино с $$$a$$$ точками на одной половине и $$$b$$$ точками на другой половине. Комплект состоит ровно из $$$21$$$ домино. Вот иллюстрация всех домино из набора:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/c0af1232a8eb0528d3b253076327de1ea68a5f4c.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А также у Анади есть граф без петель и кратных ребер. Он хочет выбрать некоторые домино и поставить их на ребра графа. Когда он ставит домино на ребро, он также выбирает его направления. Иначе говоря, одна половинка домино должна быть направлена в сторону одного конца ребра, а другая половинка в сторону другого конца ребра. На каждое ребро можно поставить не более одного домино. Необязательно ставить домино на все ребра графа.</p><p>Но также есть одно дополнительно условие: если несколько половинок домино направлены к одной и той же вершине, все эти половинки должны содержать одинаковое число точек.</p><p>Какое максимальное количество домино Анади может расставить на ребрах графа?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$1 \leq n \leq 7$$$, $$$0 \leq m \leq \frac{n\cdot(n-1)}{2}$$$) — количество вершин и ребер графа.</p><p>В каждой из следующих $$$m$$$ строк записано по два целых числа. Числа в $$$i$$$-й строке это $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a, b \leq n$$$, $$$a \neq b$$$), описывающих ребро в графе, соединяющее вершины $$$a_i$$$ и $$$b_i$$$.</p><p>Гарантируется, что никакое ребро не соединяет вершину саму с собой, а также между каждой парой вершин есть не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальное количество домино, которое Анади может расставить на ребрах графа.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 21 1 2 1 3 1 4 1 5 1 6 1 7 2 3 2 4 2 5 2 6 2 7 3 4 3 5 3 6 3 7 4 5 4 6 4 7 5 6 5 7 6 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 16 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Иллюстрация к графу Анади из первого примера:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/df00f21dd17822a0cdf733362092fced4af74b04.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>А вот один из способов расставить на его ребрах домино:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/0b4527d640281374049f8f0d9df6d0913547e766.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Обратите внимание, что к каждой вершине направлены половинки домино с одинаковым числом точек. Например, все половинки направленные к вершины $$$1$$$ содержат три точки.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483cae8c19d4f',t:'MTY5NjY2NDYyNC4zMzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1210B
1210
B
ru
B. Марчин и сборы
<div class="problem-statement"><div class="header"><div class="title">B. Марчин и сборы</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>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</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="5ed939aea3350cf148f95642d896cdec"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='5ed939aea3350cf148f95642d896cdec'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='5ed939aea3350cf148f95642d896cdec'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='5ed939aea3350cf148f95642d896cdec'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='5ed939aea3350cf148f95642d896cdec'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417809"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5ed939aea3350cf148f95642d896cdec'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417809"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_78ace5344e39d79e7adf853c87b8d6d11ee310d9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Рассмотрим студентов. Они пронумерованы целыми числами от $$$1$$$ до $$$n$$$. Каждый из них описывается двумя целыми числами $$$a_i$$$ и $$$b_i$$$; $$$b_i$$$ равно опыту $$$i$$$-го участника (чем больше, тем лучше). А также есть $$$60$$$ известных алгоритмов, которые пронумерованы целыми числами от $$$0$$$ до $$$59$$$. Если $$$i$$$-й студент знает $$$j$$$-й алгоритм, тогда $$$j$$$-й бит ($$$2^j$$$) равен единице в двоичной записи $$$a_i$$$. Иначе, он равен нулю.</p><p>Студент $$$x$$$ считает, что он лучше студента $$$y$$$ если и только если $$$x$$$ знает какой-то алгоритм, который не знает $$$y$$$. Обратите внимание, что два студента могут считать, что они лучше друг друга. Группа студентов может работать спокойно, если ни один студент из группы не считает, что он лучше всех остальных в этой группе.</p><p>Марчин хочет отправить группу из хотя бы двух студентов, которые могут работать вместе и имеют максимально возможную сумму уровней опыта. Чему равна эта сумма?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$1 \leq n \leq 7000$$$) — количество студентов, заинтересованных в сборах.</p><p>Во второй строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$a_i$$$ ($$$0 \leq a_i &lt; 2^{60}$$$).</p><p>В третьей строке записаны $$$n$$$ целых чисел. $$$i$$$-е из них это $$$b_i$$$ ($$$1 \leq b_i \leq 10^9$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число, которое равно максимальной сумме $$$b_i$$$ студентов в группе, в которой студенты могут работать спокойно. Если не существует группы из хотя бы двух студентов, в которой студенты могут работать спокойно, выведите <span class="tex-font-style-tt">0</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 3 2 3 6 2 8 5 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 0 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере оптимально отправить на сборы первого, второго, и третьего студента. Также возможно отправить только первого и третьего студента, но сумма $$$b_i$$$ у них будет меньше.</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 10:43: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:'812483d5e9361660',t:'MTY5NjY2NDYyNS43MjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1210C
1210
C
ru
C. Камил и проведение стрима
<div class="problem-statement"><div class="header"><div class="title">C. Камил и проведение стрима</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$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 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.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="5fce7a20f7f7ab2f9e507d96fd27084e"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='5fce7a20f7f7ab2f9e507d96fd27084e'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='5fce7a20f7f7ab2f9e507d96fd27084e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='5fce7a20f7f7ab2f9e507d96fd27084e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='5fce7a20f7f7ab2f9e507d96fd27084e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417810"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5fce7a20f7f7ab2f9e507d96fd27084e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417810"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2ec283d4da5dcf59e9bbb78dd62a916cc25995f8"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>768 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Камил любит стримить видео по спортивному программированию. Его канал на MeTube недавно набрал $$$100$$$ миллионов подписчиков. Чтобы отпраздновать это, он выложил видео с интересной задачей, которую он пока не может решить. Можете ли вы помочь ему?</p><p>Вам дано дерево — связный неориентированный граф состоящий из $$$n$$$ вершин и $$$n - 1$$$ ребер. Дерево подвешено за вершину $$$1$$$. Вершина $$$u$$$ является <span class="tex-font-style-it">предком</span> $$$v$$$ если она лежит на кратчайшем пути между корнем и $$$v$$$. В частности, вершина является предком себя.</p><p>У каждой вершины $$$v$$$ есть <span class="tex-font-style-it">красота</span> $$$x_v$$$ — неотрицательное целое число не большее $$$10^{12}$$$. Это позволяет нам определить красоту пути. Пусть $$$u$$$ предок $$$v$$$. Тогда определим красоту $$$f(u, v)$$$ как наибольший общий делитель красот всех вершин на кратчайшем пути между $$$u$$$ и $$$v$$$. Формально, если $$$u=t_1, t_2, t_3, \dots, t_k=v$$$ — вершины на кратчайшем пути между $$$u$$$ и $$$v$$$, тогда $$$f(u, v) = \gcd(x_{t_1}, x_{t_2}, \dots, x_{t_k})$$$. Тут $$$\gcd$$$ обозначает наибольший общий делитель множества чисел. В частности, $$$f(u, u) = \gcd(x_u) = x_u$$$.</p><p>Ваша задача найти сумму</p><p>$$$$$$ \sum_{u\text{ предок }v} f(u, v). $$$$$$</p><p>Так как ответ может быть слишком большим, выведите его по модулю $$$10^9 + 7$$$.</p><p>Обратите внимание что для любого $$$y$$$, $$$\gcd(0, y) = \gcd(y, 0) = y$$$. В частности, $$$\gcd(0, 0) = 0$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$2 \le n \le 100\,000$$$) — количество вершин в дереве.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$0 \le x_i \le 10^{12}$$$). Значение $$$x_v$$$ обозначает красоту вершины $$$v$$$.</p><p>В следующих $$$n - 1$$$ строках описаны ребра дерева. Каждая из них содержит два целых числа $$$a, b$$$ ($$$1 \le a, b \le n$$$, $$$a \neq b$$$) — вершины соединенные ребром.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму красот всех таких путей $$$(u, v)$$$, что $$$u$$$ предок $$$v$$$. Эта сумма должна быть выведена по модулю $$$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 4 5 6 0 8 1 2 1 3 1 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 42 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 0 2 3 0 0 0 0 1 2 1 3 2 4 2 5 3 6 3 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 30 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На следующей иллюстрации изображены все $$$10$$$ возможных путей, в которых один из концов является предком другого. Сумма красот всех этих путей равна $$$42$$$:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e686611ec2a6573e6e05680089e5474edc45f3b3.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 10:43: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:'812483de7aeb75b7',t:'MTY5NjY2NDYyNy4wOTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0418\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\u0435\u0440\u0435\u0432\u044c\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*2000"]
1210D
1210
D
ru
D. Конрад и оценка компании
<div class="problem-statement"><div class="header"><div class="title">D. Конрад и оценка компании</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$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 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.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="a96e4f3a69469e0118564663ae64eb9f"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='a96e4f3a69469e0118564663ae64eb9f'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='a96e4f3a69469e0118564663ae64eb9f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='a96e4f3a69469e0118564663ae64eb9f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a96e4f3a69469e0118564663ae64eb9f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417811"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a96e4f3a69469e0118564663ae64eb9f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417811"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_61856cb06c658529901aff2812b9f5f98c12abf5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Конрад — консультант по человеческим отношениям, работающий в VoltModder, крупном производителе электрооборудования. Сегодня ему было поручено оценить уровень счастья в компании.</p><p>В VoltModder работает $$$n$$$ человек, пронумерованных от $$$1$$$ до $$$n$$$. Каждый работник зарабатывает разное число денег — изначально, $$$i$$$-й человек зарабатывает $$$i$$$ рублей в день.</p><p>В каждый из $$$q$$$ следующих дней, зарплаты будут пересмотрены. В конце $$$i$$$-го дня работник $$$v_i$$$ начнет получать $$$n+i$$$ рублей в день и станет самым оплачиваемым работником в компании. Его зарплата будет оставаться такой же до её следующего пересмотра.</p><p>Некоторые пары людей не любят друг друга. Это создает в компании большое психологическое напряжение. Формально, если два человека $$$a$$$ и $$$b$$$ не любят друга друга, и $$$a$$$ зарабатывает больше денег, чем $$$b$$$, работник $$$a$$$ похвастается этим $$$b$$$. <span class="tex-font-style-it">Опасная тройка</span> это тройка из трех таких работников $$$a$$$, $$$b$$$ и $$$c$$$, что $$$a$$$ похвастается $$$b$$$, который, в свою очередь, похвастается $$$c$$$. Если $$$a$$$ не любит $$$b$$$, то и $$$b$$$ не любит $$$a$$$.</p><p>В начале каждого дня, Конрад должен посчитать количество <span class="tex-font-style-it">опасных троек</span> в компании. Можете ли вы ему помочь в этом?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100\,000$$$, $$$0 \le m \le 100\,000$$$) — количество работников в компании и количество пар работников, которые не любят друг друга. Каждая из следующих $$$m$$$ строк содержит по два целых числа $$$a_i$$$, $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$, $$$a_i \neq b_i$$$) описывающих, что работники $$$a_i$$$ и $$$b_i$$$ ненавидят друг друга (то есть $$$a_i$$$ не любит $$$b_i$$$ и $$$b_i$$$ не любит $$$a_i$$$). Каждое такое взаимоотношение будет упомянуто ровно один раз.</p><p>В следующей строке записано целое число $$$q$$$ ($$$0 \le q \le 100\,000$$$) — количество пересмотров зарплаты. $$$i$$$-я из следующих $$$q$$$ строк содержит одно целое число $$$v_i$$$ ($$$1 \le v_i \le n$$$), описывающее, что в конце $$$i$$$-го дня, работник $$$v_i$$$ будет получать больше всего денег.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q + 1$$$ целое число. $$$i$$$-е из них должно содержать количество <span class="tex-font-style-it">опасных троек</span> в компании в начале $$$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 5 1 2 2 4 1 3 3 4 2 3 2 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 1 3 5 1 2 2 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример. $$$i$$$-я строка в следующей иллюстрации показывает структуру компании в $$$i$$$-й день. Ориентированное ребро из $$$a$$$ в $$$b$$$ описывает, что работник $$$a$$$ похвастается работнику $$$b$$$. Опасные тройки показаны подсвеченными ребрами.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/baac8da0b128e437cba1696d02a8f97308396dc3.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 10:43: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:'812483e6fbbe1622',t:'MTY5NjY2NDYyOC40MzEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "*2400"]
1210E
1210
E
ru
E. Войтек и карточные фокусы
<div class="problem-statement"><div class="header"><div class="title">E. Войтек и карточные фокусы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.5 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Войтек только что выиграл олимпиаду по математике в Байтландии! Приз восхитителен - отличная книга под названием 'Карточные фокусы для чайников.' 'Отлично!' он подумал, 'Наконец-то я смогу воспользоваться запылившейся колодой карт, которая без дела лежит у меня на столе!'</p><p>Первая глава книги это 'Как перемешать $$$k$$$ карт в любом порядке, который вы хотите.' Формально это список из $$$n$$$ детерминированных методов перемешать $$$k$$$ карт. Более формально, $$$i$$$-й метод может быть описан перестановкой $$$(P_{i,1}, P_{i,2}, \dots, P_{i,k})$$$ целых чисел от $$$1$$$ до $$$k$$$. Если мы упорядочим карты в колоде от $$$1$$$ до $$$k$$$ сверху вниз, тогда $$$P_{i,j}$$$ обозначает номер $$$j$$$-й карты сверху колоды после перемешивания.</p><p>Войтек хочет научиться только некоторым фокусам сегодня. Он выберет два целых числа $$$l, r$$$ ($$$1 \le l \le r \le n$$$), и запомнит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Затем он возьмет отсортированную колоду из $$$k$$$ карт и будет применять случайные запомненные фокусы, пока ему не станет скучно. Он все еще любит математику, и поэтому заинтересовался: а сколько различных колод он может получить?</p><p>Войтек все еще не выбрал $$$l$$$ и $$$r$$$, но ему очень любопытно. Так он определил $$$f(l, r)$$$ как количество различных колод которое он может получить, если выучит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Чему равно</p><p>$$$$$$\sum_{l=1}^n \sum_{r=l}^n f(l, r)?$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le k \le 5$$$) — количество фокус и карт в колоде Войтека.</p><p>Каждая из следующих $$$n$$$ строк описывает один фокус и содержит $$$k$$$ различных целых чисел $$$P_{i,1}, P_{i,2}, \dots, P_{i, k}$$$ ($$$1 \le P_{i, j} \le k$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму, описанную в условии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 3 3 1 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 1 3 2 4 3 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 31 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> Первый фокус меняет две верхние карты. </li><li> Второй фокус берет карту снизу колоды и кладет ее наверх. </li><li> Третий фокус меняет две нижние карты. </li></ul><p>Первый и третий фокусы сами по себе позволяют получить только две колоды (либо две карты поменяны местами, либо нет). Таким образом, $$$f(1, 1) = f(3, 3) = 2$$$.</p><p>Второй фокус позволяет совершать циклические сдвиги, таким образом $$$f(2,2)=3$$$.</p><p>Оказывается, что два первых и два последних фокуса позволяют получить все возможные перестановки колоды Войтека. Таким образом $$$f(1,2) = f(2,3) = f(1,3) = 3! = 6$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7d2fbac86e04d26b03f23ae6adbd7553"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='7d2fbac86e04d26b03f23ae6adbd7553'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='7d2fbac86e04d26b03f23ae6adbd7553'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='7d2fbac86e04d26b03f23ae6adbd7553'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='7d2fbac86e04d26b03f23ae6adbd7553'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417812"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7d2fbac86e04d26b03f23ae6adbd7553'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417812"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c769724b9486559d161c64ba6e17ad775be6074d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Войтек только что выиграл олимпиаду по математике в Байтландии! Приз восхитителен - отличная книга под названием 'Карточные фокусы для чайников.' 'Отлично!' он подумал, 'Наконец-то я смогу воспользоваться запылившейся колодой карт, которая без дела лежит у меня на столе!'</p><p>Первая глава книги это 'Как перемешать $$$k$$$ карт в любом порядке, который вы хотите.' Формально это список из $$$n$$$ детерминированных методов перемешать $$$k$$$ карт. Более формально, $$$i$$$-й метод может быть описан перестановкой $$$(P_{i,1}, P_{i,2}, \dots, P_{i,k})$$$ целых чисел от $$$1$$$ до $$$k$$$. Если мы упорядочим карты в колоде от $$$1$$$ до $$$k$$$ сверху вниз, тогда $$$P_{i,j}$$$ обозначает номер $$$j$$$-й карты сверху колоды после перемешивания.</p><p>Войтек хочет научиться только некоторым фокусам сегодня. Он выберет два целых числа $$$l, r$$$ ($$$1 \le l \le r \le n$$$), и запомнит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Затем он возьмет отсортированную колоду из $$$k$$$ карт и будет применять случайные запомненные фокусы, пока ему не станет скучно. Он все еще любит математику, и поэтому заинтересовался: а сколько различных колод он может получить?</p><p>Войтек все еще не выбрал $$$l$$$ и $$$r$$$, но ему очень любопытно. Так он определил $$$f(l, r)$$$ как количество различных колод которое он может получить, если выучит все фокусы от $$$l$$$-го до $$$r$$$-го, включительно. Чему равно</p><p>$$$$$$\sum_{l=1}^n \sum_{r=l}^n f(l, r)?$$$$$$</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано два целых числа $$$n$$$, $$$k$$$ ($$$1 \le n \le 200\,000$$$, $$$1 \le k \le 5$$$) — количество фокус и карт в колоде Войтека.</p><p>Каждая из следующих $$$n$$$ строк описывает один фокус и содержит $$$k$$$ различных целых чисел $$$P_{i,1}, P_{i,2}, \dots, P_{i, k}$$$ ($$$1 \le P_{i, j} \le k$$$).</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите сумму, описанную в условии.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 1 3 3 1 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 25 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 1 3 2 4 3 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 31 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Рассмотрим первый пример:</p><ul> <li> Первый фокус меняет две верхние карты. </li><li> Второй фокус берет карту снизу колоды и кладет ее наверх. </li><li> Третий фокус меняет две нижние карты. </li></ul><p>Первый и третий фокусы сами по себе позволяют получить только две колоды (либо две карты поменяны местами, либо нет). Таким образом, $$$f(1, 1) = f(3, 3) = 2$$$.</p><p>Второй фокус позволяет совершать циклические сдвиги, таким образом $$$f(2,2)=3$$$.</p><p>Оказывается, что два первых и два последних фокуса позволяют получить все возможные перестановки колоды Войтека. Таким образом $$$f(1,2) = f(2,3) = f(1,3) = 3! = 6$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483ef5b711498',t:'MTY5NjY2NDYyOS43OTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2700"]
1210F1
1210
F1
ru
F1. Марек и паросочетания (упрощенная версия)
<div class="problem-statement"><div class="header"><div class="title">F1. Марек и паросочетания (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это упрощённая версия задачи. В этой версии, $$$n \le 6$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 6}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$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> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</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="ef881ef7ce40f03056b781c9f39f97d3"/> <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="Задача - F1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='ef881ef7ce40f03056b781c9f39f97d3'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%2Fproblem%2FF1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='ef881ef7ce40f03056b781c9f39f97d3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='ef881ef7ce40f03056b781c9f39f97d3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='ef881ef7ce40f03056b781c9f39f97d3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417813"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ef881ef7ce40f03056b781c9f39f97d3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417813"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="F1" data-uuid="ps_616591ee7dd6771d8baa52fb4af039c9774c96fc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">F1. Марек и паросочетания (упрощенная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>7 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это упрощённая версия задачи. В этой версии, $$$n \le 6$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 6}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$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> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812483f7f9fc15f2',t:'MTY5NjY2NDYzMS4xMzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3100"]
1210F2
1210
F2
ru
F2. Марек и паросочетания (усложненная версия)
<div class="problem-statement"><div class="header"><div class="title">F2. Марек и паросочетания (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это усложненная версия задачи. В этой версии, $$$n \le 7$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 7}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$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> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</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="93a736231ae07384563573b960c92657"/> <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="Задача - F2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - F2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='93a736231ae07384563573b960c92657'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%2Fproblem%2FF2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='93a736231ae07384563573b960c92657'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='93a736231ae07384563573b960c92657'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='93a736231ae07384563573b960c92657'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417814"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='93a736231ae07384563573b960c92657'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417814"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="F2" data-uuid="ps_7967fe47c7144634c6d673aa23b83418222bd298"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">F2. Марек и паросочетания (усложненная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>15 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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">Это усложненная версия задачи. В этой версии, $$$n \le 7$$$.</span></p><p>Марек работает над тестами для новой задачи. Хотите узнать, для какой? Не-а, мы вам не скажем. Однако, мы скажем вам как он генерирует тесты.</p><p>Марек выбирает целое число $$$n$$$ и $$$n^2$$$ целых чисел $$$p_{ij}$$$ ($$$1 \le i \le n$$$, $$$1 \le j \le n$$$). Затем он генерирует случайный двудольный граф на $$$2n$$$ вершин. В этом графе есть $$$n$$$ вершин у левой доли: $$$\ell_1, \ell_2, \dots, \ell_n$$$, и $$$n$$$ вершин у правой доли: $$$r_1, r_2, \dots, r_n$$$. Для каждой пары $$$i$$$ и $$$j$$$, он добавляет в граф ребро между вершинами $$$\ell_i$$$ и $$$r_j$$$ с вероятностью $$$p_{ij}$$$ процентов.</p><p>Оказывается, что тест будет сильным, если в этом графе есть совершенное паросочетание. Какова вероятность, что это произойдет?</p><p>Можно показать, что ответ можно представить в виде $$$\frac{P}{Q}$$$, где $$$P$$$ и $$$Q$$$ взаимно простые целое число и $$$Q \not\equiv 0 \pmod{10^9+7}$$$. Обозначим за $$$Q^{-1}$$$ целое число, для которого верно $$$Q \cdot Q^{-1} \equiv 1 \pmod{10^9+7}$$$. Выведите значение $$$P \cdot Q^{-1}$$$ по модулю $$$10^9+7$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$\mathbf{1 \le n \le 7}$$$). Следующие $$$n$$$ строк описывают вероятности появления каждого ребра в графе. $$$i$$$-й из них содержит $$$n$$$ целых чисел $$$p_{i1}, p_{i2}, \dots, p_{in}$$$ ($$$0 \le p_{ij} \le 100$$$); $$$p_{ij}$$$ описывает вероятность, в процентах, наличия в графе ребра между вершинами $$$\ell_i$$$ и $$$r_j$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — вероятность, что в двудольном графе есть совершенное паросочетание, записанная как $$$P \cdot Q^{-1} \pmod{10^9+7}$$$ для $$$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> 2 50 50 50 50 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 937500007 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 4 1 5 9 2 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 351284554 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, каждый из $$$16$$$ графов равновероятен. Из них у $$$7$$$ есть совершенное паросочетание: </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3ac01dc2f694b6d73d26038b1cbcb1fd33301344.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Таким образом, вероятность равна $$$\frac{7}{16}$$$. Так как $$$16 \cdot 562\,500\,004 = 1 \pmod{10^9+7}$$$, ответ на тест равен $$$7 \cdot 562\,500\,004 \mod{(10^9+7)} = 937\,500\,007$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812484003e7c9d70',t:'MTY5NjY2NDYzMi40NjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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"]
["\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0442\u0435\u043e\u0440\u0438\u044f \u0432\u0435\u0440\u043e\u044f\u0442\u043d\u043e\u0441\u0442\u0435\u0439", "*3200"]
1210G
1210
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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Матеуш любит путешевствовать! Однако, на его $$$42$$$-м визите Санкт-Компьютерсбурга осталось не так много достопримечательностей для осмотра. Поэтому он решил отправиться со своими друзьями в эскейп-рум!</p><p>Команда с легкостью разгадала почти все загадки. Осталось только одна — большой круглый стол! Есть $$$n$$$ весов, лежащих на поверхности стола, распределенных по окружности. Каждые весы соседствуют ровно двум другим весами: для каждого $$$i \in \{1, 2, \dots, n-1\}$$$, $$$i$$$-е и $$$(i+1)$$$-е весы являются соседними, а также соседними являются первые и $$$n$$$-е весы.</p><p>Изначально на $$$i$$$-х весах лежат $$$a_i$$$ тяжелых монет. Матеуш может совершать движения — каждое движение состоит из взятия одной монеты с одних весов и перекладывания ее на соседние весы.</p><p>Оказывается, что загадка будет решена только если соблюдаются некоторые условия на количества монет на каждых весах. А именно, у каждых весов есть параметры $$$l_i$$$ и $$$r_i$$$. Если каждая монета лежит на ровно одних весах, и для каждого $$$i$$$, на $$$i$$$-х весах лежат хотя бы $$$l_i$$$ и не более $$$r_i$$$ монет, загадка будет решена и команда Матеуша выиграет!</p><p>Матеуш нацелен на как можно лучшее время. Разумеется, он хочет решить загадку как можно быстрее. Какое минимальное количество действий требуется совершить, чтобы удовлетворить всем условиям?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 35\,000$$$) — количество весов на круге.</p><p>Следующие $$$n$$$ строк описывают весы. $$$i$$$-я из них описывает $$$i$$$-е весы и содержит три целых числа $$$a_i, l_i, r_i$$$ ($$$0 \le a_i \le 35\,000$$$, $$$0 \le l_i \le r_i \le 35\,000$$$).</p><p>Гарантируется, что загадка разрешима, а именно $$$\sum_{i=1}^n l_i \le \sum_{i=1}^n a_i \le \sum_{i=1}^n r_i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество операций, которое нужно сделать, чтобы решить загадку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 1 2 3 0 3 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0 2 3 3 3 4 0 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ce6d0f29ca6a3009b0cedd3c2c1d6661"/> <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="71c1e415ac98b8a63a4cb563faf0a11c88f1f65e"/> <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='ce6d0f29ca6a3009b0cedd3c2c1d6661'>&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><a href="/dasha"><img style="height:50px;position:relative;top:4px;" src="https://assets.codeforces.com/images/dasha-logo.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%2F1210%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='ce6d0f29ca6a3009b0cedd3c2c1d6661'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1210">Dasha Code Championship - СПб Финал (только для онсайт-финалистов)</a></th> </tr> <tr> <td class="left 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='ce6d0f29ca6a3009b0cedd3c2c1d6661'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1210/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='ce6d0f29ca6a3009b0cedd3c2c1d6661'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="417815"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ce6d0f29ca6a3009b0cedd3c2c1d6661'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="417815"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69958" title="69958" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="13230" resourceName="69958" 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/70008" title="Dasha Code Championship Finals and Mirror Round 588 Editorial" target="_blank">Разбор задач <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9405" resourceName="Dasha Code Championship Finals and Mirror Round 588 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/1210">Задачи</a></li> <li><a href="/contest/1210/submit">Отослать</a></li> <li><a href="/contest/1210/my">Мои посылки</a></li> <li><a href="/contest/1210/status">Статус</a></li> <li><a href="/contest/1210/hacks">Взломы</a></li> <li><a href="/contest/1210/room/1">Комната</a></li> <li><a href="/contest/1210/standings">Положение</a></li> <li><a href="/contest/1210/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_09802e1b4a26fb6242d0e4ff06de705bc785bfa2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Матеуш любит путешевствовать! Однако, на его $$$42$$$-м визите Санкт-Компьютерсбурга осталось не так много достопримечательностей для осмотра. Поэтому он решил отправиться со своими друзьями в эскейп-рум!</p><p>Команда с легкостью разгадала почти все загадки. Осталось только одна — большой круглый стол! Есть $$$n$$$ весов, лежащих на поверхности стола, распределенных по окружности. Каждые весы соседствуют ровно двум другим весами: для каждого $$$i \in \{1, 2, \dots, n-1\}$$$, $$$i$$$-е и $$$(i+1)$$$-е весы являются соседними, а также соседними являются первые и $$$n$$$-е весы.</p><p>Изначально на $$$i$$$-х весах лежат $$$a_i$$$ тяжелых монет. Матеуш может совершать движения — каждое движение состоит из взятия одной монеты с одних весов и перекладывания ее на соседние весы.</p><p>Оказывается, что загадка будет решена только если соблюдаются некоторые условия на количества монет на каждых весах. А именно, у каждых весов есть параметры $$$l_i$$$ и $$$r_i$$$. Если каждая монета лежит на ровно одних весах, и для каждого $$$i$$$, на $$$i$$$-х весах лежат хотя бы $$$l_i$$$ и не более $$$r_i$$$ монет, загадка будет решена и команда Матеуша выиграет!</p><p>Матеуш нацелен на как можно лучшее время. Разумеется, он хочет решить загадку как можно быстрее. Какое минимальное количество действий требуется совершить, чтобы удовлетворить всем условиям?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$n$$$ ($$$3 \le n \le 35\,000$$$) — количество весов на круге.</p><p>Следующие $$$n$$$ строк описывают весы. $$$i$$$-я из них описывает $$$i$$$-е весы и содержит три целых числа $$$a_i, l_i, r_i$$$ ($$$0 \le a_i \le 35\,000$$$, $$$0 \le l_i \le r_i \le 35\,000$$$).</p><p>Гарантируется, что загадка разрешима, а именно $$$\sum_{i=1}^n l_i \le \sum_{i=1}^n a_i \le \sum_{i=1}^n r_i$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное количество операций, которое нужно сделать, чтобы решить загадку.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 2 3 1 2 3 4 3 3 4 3 3 4 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 1 2 3 0 3 1 0 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0 2 3 3 3 4 0 4 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812484088833160a',t:'MTY5NjY2NDYzMy44MTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1212A
1212
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><ul> <li> если последняя цифра числа не равна нулю, она уменьшает число на единицу; </li><li> если последняя цифра числа равна нулю, она делит число на 10 (то есть удаляет его последнюю цифру). </li></ul><p>Вам задано целое число $$$n$$$. Таня хочет вычесть из него единицу $$$k$$$ раз. Ваша задача вывести результат после всех $$$k$$$ вычитаний.</p><p>Гарантируется, что ответ будет являться целым положительным числом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 50$$$) — число, из которого Таня хочет вычитать единицу и количество вычитаний соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — результат вычитания из $$$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>512 4<br/></pre></div><div class="output"><div class="title">Выходные данные</div><pre>50<br/></pre></div><div class="input"><div class="title">Входные данные</div><pre>1000000000 9<br/></pre></div><div class="output"><div class="title">Выходные данные</div><pre>1<br/></pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере последовательность преобразований будет выглядеть так: $$$512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$$$.</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="ec635b1f852dd167c34990bde5cd7eb3"/> <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="cec6f22a09e7cb84d5c32345e1d1ee36aabc0087"/> <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='ec635b1f852dd167c34990bde5cd7eb3'>&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><a href="/kotlin"><img style="position:relative;top:4px;height:55px;right:1px;" src="//assets.codeforces.com/images/kh/kotlin_heroes_2021_page_header.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%2F1212%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='ec635b1f852dd167c34990bde5cd7eb3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1212">Kotlin Heroes: Practice 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 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;">Kotlin Heroes: Practice 2:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Kotlin 1.6.10</li> <li>Kotlin 1.7.20</li> </ul> </div> </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='ec635b1f852dd167c34990bde5cd7eb3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="400932"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ec635b1f852dd167c34990bde5cd7eb3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="400932"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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="https://codeforces.com/blog/entry/69419" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9293" 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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1212">Задачи</a></li> <li><a href="/contest/1212/submit">Отослать</a></li> <li><a href="/contest/1212/my">Мои посылки</a></li> <li><a href="/contest/1212/status">Статус</a></li> <li><a href="/contest/1212/standings">Положение</a></li> <li><a href="/contest/1212/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f4d21dda8ed68f6f8cdfc296811185caa597dd07"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><ul> <li> если последняя цифра числа не равна нулю, она уменьшает число на единицу; </li><li> если последняя цифра числа равна нулю, она делит число на 10 (то есть удаляет его последнюю цифру). </li></ul><p>Вам задано целое число $$$n$$$. Таня хочет вычесть из него единицу $$$k$$$ раз. Ваша задача вывести результат после всех $$$k$$$ вычитаний.</p><p>Гарантируется, что ответ будет являться целым положительным числом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$2 \le n \le 10^9$$$, $$$1 \le k \le 50$$$) — число, из которого Таня хочет вычитать единицу и количество вычитаний соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — результат вычитания из $$$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>512 4<br /></pre></div><div class="output"><div class="title">Выходные данные</div><pre>50<br /></pre></div><div class="input"><div class="title">Входные данные</div><pre>1000000000 9<br /></pre></div><div class="output"><div class="title">Выходные данные</div><pre>1<br /></pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере последовательность преобразований будет выглядеть так: $$$512 \rightarrow 511 \rightarrow 510 \rightarrow 51 \rightarrow 50$$$.</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 10:43: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:'81248410e9c59d3d',t:'MTY5NjY2NDYzNS4yNjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*800"]
1212B
1212
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">AZ</span>», «<span class="tex-font-style-tt">AA</span>», «<span class="tex-font-style-tt">ZA</span>» — три различные двуграммы.</p><p>Вам задана строка $$$s$$$, состоящая из $$$n$$$ прописных букв латинского алфавита. Ваша задача вывести <span class="tex-font-style-bf">любую</span> двуграмму, которая содержится в этой строке <span class="tex-font-style-bf">как подстрока</span> (то есть как два последовательных символа строки) максимальное количество раз. Например, для строки $$$s$$$ = «<span class="tex-font-style-tt">BBAABBBA</span>» ответ — это двуграмма <span class="tex-font-style-tt">BB</span>, которая встречается в $$$s$$$ три раза.</p><p>Заметьте, что вхождения двуграммы могут пересекаться друг с другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 100$$$) — длину строки $$$s$$$. Вторая строка входных данных содержит строку $$$s$$$, состоящую из $$$n$$$ прописных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одну строку, состоящую ровно из двух прописных букв латинского алфавита — <span class="tex-font-style-bf">любую</span> двуграмму, которая содержится в заданной строке $$$s$$$ <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>7<br/>ABACABA<br/></pre></div><div class="output"><div class="title">Выходные данные</div><pre>AB<br/></pre></div><div class="input"><div class="title">Входные данные</div><pre>5<br/>ZZZAA<br/></pre></div><div class="output"><div class="title">Выходные данные</div><pre>ZZ<br/></pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере «<span class="tex-font-style-tt">BA</span>» тоже может являться ответом.</p><p>Во втором тестовом примере только двуграмма «<span class="tex-font-style-tt">ZZ</span>» может быть ответом, потому что только она входит в строку «<span class="tex-font-style-tt">ZZZAA</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="681ad7d99d7ba6d84fb705f4b3fb0034"/> <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="cec6f22a09e7cb84d5c32345e1d1ee36aabc0087"/> <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='681ad7d99d7ba6d84fb705f4b3fb0034'>&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><a href="/kotlin"><img style="position:relative;top:4px;height:55px;right:1px;" src="//assets.codeforces.com/images/kh/kotlin_heroes_2021_page_header.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%2F1212%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='681ad7d99d7ba6d84fb705f4b3fb0034'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1212">Kotlin Heroes: Practice 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 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;">Kotlin Heroes: Practice 2:</div> <ul class="list" style="font-size:0.8em;margin-top:0.5em;"> <li>Kotlin 1.6.10</li> <li>Kotlin 1.7.20</li> </ul> </div> </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="Сложность"> *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='681ad7d99d7ba6d84fb705f4b3fb0034'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="400933"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='681ad7d99d7ba6d84fb705f4b3fb0034'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="400933"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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="https://codeforces.com/blog/entry/69419" title="A" target="_blank">A <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9293" 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> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1212">Задачи</a></li> <li><a href="/contest/1212/submit">Отослать</a></li> <li><a href="/contest/1212/my">Мои посылки</a></li> <li><a href="/contest/1212/status">Статус</a></li> <li><a href="/contest/1212/standings">Положение</a></li> <li><a href="/contest/1212/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1af25d9e53ee9ab5a3eac656df3c8ecfb4ea5376"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">AZ</span>», «<span class="tex-font-style-tt">AA</span>», «<span class="tex-font-style-tt">ZA</span>» — три различные двуграммы.</p><p>Вам задана строка $$$s$$$, состоящая из $$$n$$$ прописных букв латинского алфавита. Ваша задача вывести <span class="tex-font-style-bf">любую</span> двуграмму, которая содержится в этой строке <span class="tex-font-style-bf">как подстрока</span> (то есть как два последовательных символа строки) максимальное количество раз. Например, для строки $$$s$$$ = «<span class="tex-font-style-tt">BBAABBBA</span>» ответ — это двуграмма <span class="tex-font-style-tt">BB</span>, которая встречается в $$$s$$$ три раза.</p><p>Заметьте, что вхождения двуграммы могут пересекаться друг с другом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит целое число $$$n$$$ ($$$2 \le n \le 100$$$) — длину строки $$$s$$$. Вторая строка входных данных содержит строку $$$s$$$, состоящую из $$$n$$$ прописных букв латинского алфавита.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одну строку, состоящую ровно из двух прописных букв латинского алфавита — <span class="tex-font-style-bf">любую</span> двуграмму, которая содержится в заданной строке $$$s$$$ <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>7<br />ABACABA<br /></pre></div><div class="output"><div class="title">Выходные данные</div><pre>AB<br /></pre></div><div class="input"><div class="title">Входные данные</div><pre>5<br />ZZZAA<br /></pre></div><div class="output"><div class="title">Выходные данные</div><pre>ZZ<br /></pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере «<span class="tex-font-style-tt">BA</span>» тоже может являться ответом.</p><p>Во втором тестовом примере только двуграмма «<span class="tex-font-style-tt">ZZ</span>» может быть ответом, потому что только она входит в строку «<span class="tex-font-style-tt">ZZZAA</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 10:43:56</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:'8124841a0a9e16e3',t:'MTY5NjY2NDYzNi41OTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*900"]
1213A
1213
A
ru
A. Перемещение фишек
<div class="problem-statement"><div class="header"><div class="title">A. Перемещение фишек</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано $$$n$$$ фишек на числовой прямой. $$$i$$$-я фишка располагается в целочисленной координате $$$x_i$$$. Некоторые фишки <span class="tex-font-style-bf">могут иметь одинаковые координаты</span>.</p><p>Вы можете совершать любой из следующих двух типов ходов любое (возможно, нулевое) количество раз над любой фишкой:</p><ul> <li> Переместить фишку $$$i$$$ на $$$2$$$ влево или на $$$2$$$ вправо <span class="tex-font-style-bf">бесплатно</span> (то есть заменить текущую координату $$$x_i$$$ на $$$x_i - 2$$$ или $$$x_i + 2$$$); </li><li> переместить фишку $$$i$$$ на $$$1$$$ влево или на $$$1$$$ вправо и заплатить <span class="tex-font-style-bf">одну монету</span> за этот ход (то есть заменить текущую координату $$$x_i$$$ на $$$x_i - 1$$$ или $$$x_i + 1$$$). </li></ul><p>Заметьте, что разрешается перемещать фишки в любые целочисленные координаты, включая нулевую и отрицательные.</p><p>Ваша задача — найти минимальное суммарное количество монет, необходимое для того, чтобы переместить все $$$n$$$ фишек в одну координату (то есть после какой-то последовательности ходов все $$$x_i$$$ должны быть равны).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество фишек.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), где $$$x_i$$$ равно координате $$$i$$$-й фишки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное суммарное количество монет, необходимое для того, чтобы переместить все $$$n$$$ фишек в одну координату.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере вам необходимо переместить первую фишку на $$$2$$$ вправо и вторую фишку на $$$1$$$ вправо или переместить третью фишку на $$$2$$$ влево и вторую фишку на $$$1$$$ влево, таким образом ответ равен $$$1$$$.</p><p>Во втором тестовом примере вам необходимо передвинуть две фишки с координатами $$$3$$$ на $$$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="5737651bc18e8e3cb5c1dcb190d68f50"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='5737651bc18e8e3cb5c1dcb190d68f50'>&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%2F1213%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='5737651bc18e8e3cb5c1dcb190d68f50'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='5737651bc18e8e3cb5c1dcb190d68f50'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='5737651bc18e8e3cb5c1dcb190d68f50'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399399"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5737651bc18e8e3cb5c1dcb190d68f50'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399399"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_905325a1b6702e0bc59f24c84a364dc5b27be81f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ фишек на числовой прямой. $$$i$$$-я фишка располагается в целочисленной координате $$$x_i$$$. Некоторые фишки <span class="tex-font-style-bf">могут иметь одинаковые координаты</span>.</p><p>Вы можете совершать любой из следующих двух типов ходов любое (возможно, нулевое) количество раз над любой фишкой:</p><ul> <li> Переместить фишку $$$i$$$ на $$$2$$$ влево или на $$$2$$$ вправо <span class="tex-font-style-bf">бесплатно</span> (то есть заменить текущую координату $$$x_i$$$ на $$$x_i - 2$$$ или $$$x_i + 2$$$); </li><li> переместить фишку $$$i$$$ на $$$1$$$ влево или на $$$1$$$ вправо и заплатить <span class="tex-font-style-bf">одну монету</span> за этот ход (то есть заменить текущую координату $$$x_i$$$ на $$$x_i - 1$$$ или $$$x_i + 1$$$). </li></ul><p>Заметьте, что разрешается перемещать фишки в любые целочисленные координаты, включая нулевую и отрицательные.</p><p>Ваша задача — найти минимальное суммарное количество монет, необходимое для того, чтобы переместить все $$$n$$$ фишек в одну координату (то есть после какой-то последовательности ходов все $$$x_i$$$ должны быть равны).</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 100$$$) — количество фишек.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$x_1, x_2, \dots, x_n$$$ ($$$1 \le x_i \le 10^9$$$), где $$$x_i$$$ равно координате $$$i$$$-й фишки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимальное суммарное количество монет, необходимое для того, чтобы переместить все $$$n$$$ фишек в одну координату.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 2 2 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом тестовом примере вам необходимо переместить первую фишку на $$$2$$$ вправо и вторую фишку на $$$1$$$ вправо или переместить третью фишку на $$$2$$$ влево и вторую фишку на $$$1$$$ влево, таким образом ответ равен $$$1$$$.</p><p>Во втором тестовом примере вам необходимо передвинуть две фишки с координатами $$$3$$$ на $$$1$$$ влево, таким образом ответ равен $$$2$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:43: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:'812484225d8775a3',t:'MTY5NjY2NDYzOC4wMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*900"]
1213B
1213
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>Поликарп анализирует цену на новую модель berPhone. В его распоряжении цены за $$$n$$$ последних дней: $$$a_1, a_2, \dots, a_n$$$, где $$$a_i$$$ — цена berPhone в день $$$i$$$.</p><p>Поликарп считает цену в день $$$i$$$ плохой, если позже (то есть в день с большим номером) berPhone продавался по меньшей цене. Например, если $$$n=6$$$ и $$$a=[3, 9, 4, 6, 7, 5]$$$, то количество дней с плохой ценой равно $$$3$$$ — это дни $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) и $$$5$$$ ($$$a_5=7$$$).</p><p>Выведите количество дней с плохой ценой по мнению Поликарпа.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных данных в тесте. Наборы входных данных надо обрабатывать независимо, один за другим.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 150000$$$) — количество дней. Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), где $$$a_i$$$ — цена в $$$i$$$-й день.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$150000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел, $$$j$$$-е из них должно быть равно количеству дней с плохой ценой в $$$j$$$-м наборе входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 3 9 4 6 7 5 1 1000000 2 2 1 10 31 41 59 26 53 58 97 93 23 84 7 3 2 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 1 8 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="5d8775d7b82a1fe5a62c8725de1b8b3e"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='5d8775d7b82a1fe5a62c8725de1b8b3e'>&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%2F1213%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='5d8775d7b82a1fe5a62c8725de1b8b3e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='5d8775d7b82a1fe5a62c8725de1b8b3e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='5d8775d7b82a1fe5a62c8725de1b8b3e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399400"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5d8775d7b82a1fe5a62c8725de1b8b3e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399400"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_92783c2abc560846e7ab52a244c16f8bcad8e590"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Поликарп анализирует цену на новую модель berPhone. В его распоряжении цены за $$$n$$$ последних дней: $$$a_1, a_2, \dots, a_n$$$, где $$$a_i$$$ — цена berPhone в день $$$i$$$.</p><p>Поликарп считает цену в день $$$i$$$ плохой, если позже (то есть в день с большим номером) berPhone продавался по меньшей цене. Например, если $$$n=6$$$ и $$$a=[3, 9, 4, 6, 7, 5]$$$, то количество дней с плохой ценой равно $$$3$$$ — это дни $$$2$$$ ($$$a_2=9$$$), $$$4$$$ ($$$a_4=6$$$) и $$$5$$$ ($$$a_5=7$$$).</p><p>Выведите количество дней с плохой ценой по мнению Поликарпа.</p><p>Вам необходимо ответить на $$$t$$$ независимых наборов входных данных.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано целое число $$$t$$$ ($$$1 \le t \le 10000$$$) — количество наборов входных данных в тесте. Наборы входных данных надо обрабатывать независимо, один за другим.</p><p>Каждый набор входных данных состоит из двух строк. Первая строка содержит целое число $$$n$$$ ($$$1 \le n \le 150000$$$) — количество дней. Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), где $$$a_i$$$ — цена в $$$i$$$-й день.</p><p>Гарантируется, что сумма $$$n$$$ по всем наборам входных данных в тесте не превосходит $$$150000$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$t$$$ целых чисел, $$$j$$$-е из них должно быть равно количеству дней с плохой ценой в $$$j$$$-м наборе входных данных.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 6 3 9 4 6 7 5 1 1000000 2 2 1 10 31 41 59 26 53 58 97 93 23 84 7 3 2 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 0 1 8 2 </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 10:43: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:'8124842b6802160a',t:'MTY5NjY2NDYzOS4zODMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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"]
["\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"]
1213C
1213
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$$$ страниц, пронумерованных от $$$1$$$ до $$$n$$$. Каждый раз, когда он завершает читать страницу с номером, делящимся на $$$m$$$, он выписывает последнюю цифру номера страницы. Например, если $$$n=15$$$ и $$$m=5$$$, то страницы, делящиеся на $$$m$$$, имеют номера $$$5, 10, 15$$$. Их последние цифры равны $$$5, 0, 5$$$ соответственно, а их сумма равна $$$10$$$.</p><p>Ваша задача — посчитать сумму всех цифр, которые Поликарп выпишет.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 1000$$$) — количество запросов.</p><p>Следующие $$$q$$$ строк содержат запросы, по одному в строке. Каждый запрос описывается двумя целыми числами $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — количеством страниц в книге и необходимым делителем соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите ответ на него — сумму цифр, выписанных Поликарпом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 1 1 10 1 100 3 1024 14 998244353 1337 123 144 1234312817382646 13 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 45 153 294 3359835 0 427262129093995 </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="c67ceeabbc47b31cd3532aadf1bf6e26"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='c67ceeabbc47b31cd3532aadf1bf6e26'>&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%2F1213%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='c67ceeabbc47b31cd3532aadf1bf6e26'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='c67ceeabbc47b31cd3532aadf1bf6e26'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='c67ceeabbc47b31cd3532aadf1bf6e26'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399401"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c67ceeabbc47b31cd3532aadf1bf6e26'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399401"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1f5fc01773c0632f6012ab318a6f08434cec990b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ страниц, пронумерованных от $$$1$$$ до $$$n$$$. Каждый раз, когда он завершает читать страницу с номером, делящимся на $$$m$$$, он выписывает последнюю цифру номера страницы. Например, если $$$n=15$$$ и $$$m=5$$$, то страницы, делящиеся на $$$m$$$, имеют номера $$$5, 10, 15$$$. Их последние цифры равны $$$5, 0, 5$$$ соответственно, а их сумма равна $$$10$$$.</p><p>Ваша задача — посчитать сумму всех цифр, которые Поликарп выпишет.</p><p>Вам необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$q$$$ ($$$1 \le q \le 1000$$$) — количество запросов.</p><p>Следующие $$$q$$$ строк содержат запросы, по одному в строке. Каждый запрос описывается двумя целыми числами $$$n$$$ и $$$m$$$ ($$$1 \le n, m \le 10^{16}$$$) — количеством страниц в книге и необходимым делителем соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите ответ на него — сумму цифр, выписанных Поликарпом.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 1 1 10 1 100 3 1024 14 998244353 1337 123 144 1234312817382646 13 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 45 153 294 3359835 0 427262129093995 </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 10:44: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:'81248433c88b1604',t:'MTY5NjY2NDY0MC43MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1200"]
1213D1
1213
D1
ru
D1. Приравнивание делением (легкая версия)
<div class="problem-statement"><div class="header"><div class="title">D1. Приравнивание делением (легкая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между легкой и сложной версиями — количество элементов в массиве</span>.</p><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. За один ход вы можете выбрать любое $$$a_i$$$ и разделить его на $$$2$$$ с округлением вниз (иными словами, за один ход вы можете присвоить $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).</p><p>Вы можете совершать эту операцию <span class="tex-font-style-bf">любое</span> (возможно, нулевое) количество раз с <span class="tex-font-style-bf">любым</span> $$$a_i$$$.</p><p>Ваша задача — посчитать минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных чисел в массиве.</p><p><span class="tex-font-style-bf">Не забудьте, что допустимо иметь $$$a_i = 0$$$ после каких-то операций, таким образом, ответ всегда существует</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 50$$$) — количество элементов в массиве и необходимое количество равных элементов.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных элементов в массиве.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 2 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3d0398460f89dca7b54c167b548b55a8"/> <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="Задача - D1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='3d0398460f89dca7b54c167b548b55a8'>&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%2F1213%2Fproblem%2FD1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='3d0398460f89dca7b54c167b548b55a8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='3d0398460f89dca7b54c167b548b55a8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='3d0398460f89dca7b54c167b548b55a8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399402"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3d0398460f89dca7b54c167b548b55a8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399402"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="D1" data-uuid="ps_356b15403b04bf67bd282ddebab36311c5459b8e"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">D1. Приравнивание делением (легкая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между легкой и сложной версиями — количество элементов в массиве</span>.</p><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. За один ход вы можете выбрать любое $$$a_i$$$ и разделить его на $$$2$$$ с округлением вниз (иными словами, за один ход вы можете присвоить $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).</p><p>Вы можете совершать эту операцию <span class="tex-font-style-bf">любое</span> (возможно, нулевое) количество раз с <span class="tex-font-style-bf">любым</span> $$$a_i$$$.</p><p>Ваша задача — посчитать минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных чисел в массиве.</p><p><span class="tex-font-style-bf">Не забудьте, что допустимо иметь $$$a_i = 0$$$ после каких-то операций, таким образом, ответ всегда существует</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 50$$$) — количество элементов в массиве и необходимое количество равных элементов.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных элементов в массиве.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 2 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'8124843c3d987b37',t:'MTY5NjY2NDY0Mi4wNzkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1213D2
1213
D2
ru
D2. Приравнивание делением (сложная версия)
<div class="problem-statement"><div class="header"><div class="title">D2. Приравнивание делением (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между легкой и сложной версиями — количество элементов в массиве</span>.</p><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. За один ход вы можете выбрать любое $$$a_i$$$ и разделить его на $$$2$$$ с округлением вниз (иными словами, за один ход вы можете присвоить $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).</p><p>Вы можете совершать эту операцию <span class="tex-font-style-bf">любое</span> (возможно, нулевое) количество раз с <span class="tex-font-style-bf">любым</span> $$$a_i$$$.</p><p>Ваша задача — посчитать минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных чисел в массиве.</p><p><span class="tex-font-style-bf">Не забудьте, что допустимо иметь $$$a_i = 0$$$ после каких-то операций, таким образом, ответ всегда существует</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — количество элементов в массиве и необходимое количество равных элементов.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных элементов в массиве.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 2 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d3b1d6a843546e0b8ff4e78a377b5482"/> <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="Задача - D2 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - D2 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='d3b1d6a843546e0b8ff4e78a377b5482'>&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%2F1213%2Fproblem%2FD2%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='d3b1d6a843546e0b8ff4e78a377b5482'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='d3b1d6a843546e0b8ff4e78a377b5482'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='d3b1d6a843546e0b8ff4e78a377b5482'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399403"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d3b1d6a843546e0b8ff4e78a377b5482'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399403"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="D2" data-uuid="ps_9731bc23f0e6a3d3d93c4bd83bf5fcbf49b8cae9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">D2. Приравнивание делением (сложная версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между легкой и сложной версиями — количество элементов в массиве</span>.</p><p>Вам задан массив $$$a$$$, состоящий из $$$n$$$ целых чисел. За один ход вы можете выбрать любое $$$a_i$$$ и разделить его на $$$2$$$ с округлением вниз (иными словами, за один ход вы можете присвоить $$$a_i := \lfloor\frac{a_i}{2}\rfloor$$$).</p><p>Вы можете совершать эту операцию <span class="tex-font-style-bf">любое</span> (возможно, нулевое) количество раз с <span class="tex-font-style-bf">любым</span> $$$a_i$$$.</p><p>Ваша задача — посчитать минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных чисел в массиве.</p><p><span class="tex-font-style-bf">Не забудьте, что допустимо иметь $$$a_i = 0$$$ после каких-то операций, таким образом, ответ всегда существует</span>.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le k \le n \le 2 \cdot 10^5$$$) — количество элементов в массиве и необходимое количество равных элементов.</p><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2 \cdot 10^5$$$), где $$$a_i$$$ равно $$$i$$$-му элементу $$$a$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — минимально возможное количество операций, необходимое для того, чтобы получить хотя бы $$$k$$$ равных элементов в массиве.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 2 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 1 2 3 3 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D2]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'81248444bd6b16b7',t:'MTY5NjY2NDY0My4zNjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1600"]
1213E
1213
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>Вам задано две строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-bf">обе длины $$$2$$$</span> и состоящие только из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p><p>Возможные примеры строк $$$s$$$ и $$$t$$$: «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ca</span>», «<span class="tex-font-style-tt">bb</span>».</p><p>Вам необходимо найти строку $$$res$$$, состоящую из $$$3n$$$ символов, $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">a</span>', $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">b</span>' и $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">c</span>', а также $$$s$$$ и $$$t$$$ не должны встречаться в $$$res$$$ в качестве подстрок.</p><p>Подстрокой строки называется последовательная подпоследовательность этой строки. Таким образом, строки «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ac</span>» и «<span class="tex-font-style-tt">cc</span>» являются подстроками строки «<span class="tex-font-style-tt">abacc</span>», а строки «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">aa</span>» и «<span class="tex-font-style-tt">cb</span>» — не являются подстроками строки «<span class="tex-font-style-tt">abacc</span>».</p><p>Если существует несколько возможных ответов, вы можете вывести любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>' в результирующей строке.</p><p>Вторая строка входных данных содержит одну строку $$$s$$$ длины $$$2$$$, состоящую из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p><p>Третья строка входных данных содержит одну строку $$$t$$$ длины $$$2$$$, состоящую из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p></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>» в первой строке и строку $$$res$$$ во второй строке. $$$res$$$ должна состоять из $$$3n$$$ символов, $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">a</span>', $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">b</span>' и $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">c</span>', а также $$$s$$$ и $$$t$$$ не должны встречаться в $$$res$$$ в качестве подстрок.</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 ab bc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES acbbac </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 aa bc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES cacbacbab </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 cb ac </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES abc </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="2b02496c1cf23b0fb5de5050d11b6483"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='2b02496c1cf23b0fb5de5050d11b6483'>&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%2F1213%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='2b02496c1cf23b0fb5de5050d11b6483'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='2b02496c1cf23b0fb5de5050d11b6483'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='2b02496c1cf23b0fb5de5050d11b6483'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399404"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2b02496c1cf23b0fb5de5050d11b6483'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399404"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b89f3b1413e40b8ad7afc4b8b1d555a232fb0eb4"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам задано две строки $$$s$$$ и $$$t$$$ <span class="tex-font-style-bf">обе длины $$$2$$$</span> и состоящие только из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p><p>Возможные примеры строк $$$s$$$ и $$$t$$$: «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ca</span>», «<span class="tex-font-style-tt">bb</span>».</p><p>Вам необходимо найти строку $$$res$$$, состоящую из $$$3n$$$ символов, $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">a</span>', $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">b</span>' и $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">c</span>', а также $$$s$$$ и $$$t$$$ не должны встречаться в $$$res$$$ в качестве подстрок.</p><p>Подстрокой строки называется последовательная подпоследовательность этой строки. Таким образом, строки «<span class="tex-font-style-tt">ab</span>», «<span class="tex-font-style-tt">ac</span>» и «<span class="tex-font-style-tt">cc</span>» являются подстроками строки «<span class="tex-font-style-tt">abacc</span>», а строки «<span class="tex-font-style-tt">bc</span>», «<span class="tex-font-style-tt">aa</span>» и «<span class="tex-font-style-tt">cb</span>» — не являются подстроками строки «<span class="tex-font-style-tt">abacc</span>».</p><p>Если существует несколько возможных ответов, вы можете вывести любой.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 10^5$$$) — количество символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>' в результирующей строке.</p><p>Вторая строка входных данных содержит одну строку $$$s$$$ длины $$$2$$$, состоящую из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p><p>Третья строка входных данных содержит одну строку $$$t$$$ длины $$$2$$$, состоящую из символов '<span class="tex-font-style-tt">a</span>', '<span class="tex-font-style-tt">b</span>' и '<span class="tex-font-style-tt">c</span>'.</p></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>» в первой строке и строку $$$res$$$ во второй строке. $$$res$$$ должна состоять из $$$3n$$$ символов, $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">a</span>', $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">b</span>' и $$$n$$$ символов должны быть равны '<span class="tex-font-style-tt">c</span>', а также $$$s$$$ и $$$t$$$ не должны встречаться в $$$res$$$ в качестве подстрок.</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 ab bc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES acbbac </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 aa bc </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES cacbacbab </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 cb ac </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES abc </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 10:44: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:'8124844cacde75b7',t:'MTY5NjY2NDY0NC43MTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1900"]
1213F
1213
F
ru
F. Нестабильная сортировка строки
<div class="problem-statement"><div class="header"><div class="title">F. Нестабильная сортировка строки</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Авторы загадали строку $$$s$$$, состоящую из $$$n$$$ строчных букв латинского алфавита.</p><p>Вам задано две перестановки ее индексов (не обязательно одинаковых) $$$p$$$ и $$$q$$$ (обе длины $$$n$$$). Напомним, что перестановкой называется массив длины $$$n$$$, содержащий каждое целое число от $$$1$$$ до $$$n$$$ ровно один раз.</p><p>Для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$ выполняются следующие свойства: $$$s[p_i] \le s[p_{i + 1}]$$$ и $$$s[q_i] \le s[q_{i + 1}]$$$. Это значит, что если вы выпишете все символы $$$s$$$ в порядке индексов в перестановке, результирующая строка получится отсортированной в неубывающем порядке.</p><p>Ваша задача — восстановить <span class="tex-font-style-bf">любую</span> строку $$$s$$$ длины $$$n$$$, состоящую <span class="tex-font-style-bf">хотя бы из $$$k$$$ различных строчных букв латинского алфавита</span>, которая подходит к заданным перестановкам.</p><p>Если существует несколько возможных ответов, вы можете вывести любой.</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><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, все $$$p_i$$$ являются различными целыми числами от $$$1$$$ до $$$n$$$) — перестановку $$$p$$$.</p><p>Третья срока входных данных содержит $$$n$$$ целых чисел $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, все $$$q_i$$$ являются различными целыми числами от $$$1$$$ до $$$n$$$) — перестановку $$$q$$$.</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$$$ во второй строке. Она должна состоять ровно из $$$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> 3 2 1 2 3 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES abb </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="fbaa9da4bac8cd6fdde4d0d4ef443111"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='fbaa9da4bac8cd6fdde4d0d4ef443111'>&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%2F1213%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='fbaa9da4bac8cd6fdde4d0d4ef443111'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='fbaa9da4bac8cd6fdde4d0d4ef443111'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Префикс- и 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="Сложность"> *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='fbaa9da4bac8cd6fdde4d0d4ef443111'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399405"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='fbaa9da4bac8cd6fdde4d0d4ef443111'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399405"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9bc03cbf41e37418473364f3121a1d02e4b48dae"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Авторы загадали строку $$$s$$$, состоящую из $$$n$$$ строчных букв латинского алфавита.</p><p>Вам задано две перестановки ее индексов (не обязательно одинаковых) $$$p$$$ и $$$q$$$ (обе длины $$$n$$$). Напомним, что перестановкой называется массив длины $$$n$$$, содержащий каждое целое число от $$$1$$$ до $$$n$$$ ровно один раз.</p><p>Для всех $$$i$$$ от $$$1$$$ до $$$n-1$$$ выполняются следующие свойства: $$$s[p_i] \le s[p_{i + 1}]$$$ и $$$s[q_i] \le s[q_{i + 1}]$$$. Это значит, что если вы выпишете все символы $$$s$$$ в порядке индексов в перестановке, результирующая строка получится отсортированной в неубывающем порядке.</p><p>Ваша задача — восстановить <span class="tex-font-style-bf">любую</span> строку $$$s$$$ длины $$$n$$$, состоящую <span class="tex-font-style-bf">хотя бы из $$$k$$$ различных строчных букв латинского алфавита</span>, которая подходит к заданным перестановкам.</p><p>Если существует несколько возможных ответов, вы можете вывести любой.</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><p>Вторая строка входных данных содержит $$$n$$$ целых чисел $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$, все $$$p_i$$$ являются различными целыми числами от $$$1$$$ до $$$n$$$) — перестановку $$$p$$$.</p><p>Третья срока входных данных содержит $$$n$$$ целых чисел $$$q_1, q_2, \dots, q_n$$$ ($$$1 \le q_i \le n$$$, все $$$q_i$$$ являются различными целыми числами от $$$1$$$ до $$$n$$$) — перестановку $$$q$$$.</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$$$ во второй строке. Она должна состоять ровно из $$$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> 3 2 1 2 3 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES abb </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 10:44: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:'81248454fada16a7',t:'MTY5NjY2NDY0Ni4xMDgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\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"]
["\u0433\u0440\u0430\u0444\u044b", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u043e\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2100"]
1213G
1213
G
ru
G. Запросы на пути
<div class="problem-statement"><div class="header"><div class="title">G. Запросы на пути</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задано взвешенное дерево, состоящее из $$$n$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Вам задано $$$m$$$ запросов. $$$i$$$-й запрос задан целым числом $$$q_i$$$. В этом запросе вам необходимо посчитать количество пар вершин $$$(u, v)$$$ ($$$u &lt; v$$$) таких, что максимальный вес ребра на простом пути между $$$u$$$ и $$$v$$$ не превосходит $$$q_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 - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) и весом ребра ($$$1 \le w_i \le 2 \cdot 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Последняя строка входных данных содержит $$$m$$$ целых чисел $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), где $$$q_i$$$ равно максимальному весу ребра в $$$i$$$-м запросе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел — ответы на запросы. $$$i$$$-е число должно равняться количеству пар вершин $$$(u, v)$$$ ($$$u &lt; v$$$) таких, что максимальный вес ребра на простом пути между $$$u$$$ и $$$v$$$ не превосходит $$$q_i$$$.</p><p><span class="tex-font-style-bf">Запросы пронумерованы от $$$1$$$ до $$$m$$$ в порядке входных данных</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 7 15 21 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка, соответствующая дереву из первого тестового примера: <img class="tex-graphics" src="https://espresso.codeforces.com/72719dd3f66b3e69a28d5278fedfe14cca697350.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="a288d933094928509133f887480d8062"/> <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="58f89a7d710f2dc7e47cdc2c9d81211f49e595c9"/> <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='a288d933094928509133f887480d8062'>&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%2F1213%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='a288d933094928509133f887480d8062'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1213">Codeforces Round 582 (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='a288d933094928509133f887480d8062'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1213/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a288d933094928509133f887480d8062'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="399406"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a288d933094928509133f887480d8062'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="399406"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69433" title="Codeforces Round #582 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9682:9683" 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/69464" title="Разбор Codeforces Round #582 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10611:10612" 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/1213">Задачи</a></li> <li><a href="/contest/1213/submit">Отослать</a></li> <li><a href="/contest/1213/my">Мои посылки</a></li> <li><a href="/contest/1213/status">Статус</a></li> <li><a href="/contest/1213/hacks">Взломы</a></li> <li><a href="/contest/1213/standings">Положение</a></li> <li><a href="/contest/1213/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c2bc453f0124f9d7deb3ea9ba9d3489b740cf94b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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$$$ вершин. Напомним, что деревом называется связный граф без циклов. Вершины $$$u_i$$$ и $$$v_i$$$ соединены ребром веса $$$w_i$$$.</p><p>Вам задано $$$m$$$ запросов. $$$i$$$-й запрос задан целым числом $$$q_i$$$. В этом запросе вам необходимо посчитать количество пар вершин $$$(u, v)$$$ ($$$u &lt; v$$$) таких, что максимальный вес ребра на простом пути между $$$u$$$ и $$$v$$$ не превосходит $$$q_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 - 1$$$ строк описывает ребра дерева. Ребро $$$i$$$ обозначается тремя целыми числами $$$u_i$$$, $$$v_i$$$ и $$$w_i$$$ — номерами вершин, которые оно соединяет ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) и весом ребра ($$$1 \le w_i \le 2 \cdot 10^5$$$). Гарантируется, что заданный набор ребер образует дерево.</p><p>Последняя строка входных данных содержит $$$m$$$ целых чисел $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), где $$$q_i$$$ равно максимальному весу ребра в $$$i$$$-м запросе.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$m$$$ целых чисел — ответы на запросы. $$$i$$$-е число должно равняться количеству пар вершин $$$(u, v)$$$ ($$$u &lt; v$$$) таких, что максимальный вес ребра на простом пути между $$$u$$$ и $$$v$$$ не превосходит $$$q_i$$$.</p><p><span class="tex-font-style-bf">Запросы пронумерованы от $$$1$$$ до $$$m$$$ в порядке входных данных</span>.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 5 1 2 1 3 2 3 2 4 1 4 5 2 5 7 4 3 6 2 5 2 3 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 7 15 21 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 1 2 3 2 1 3 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Картинка, соответствующая дереву из первого тестового примера: <img class="tex-graphics" src="https://espresso.codeforces.com/72719dd3f66b3e69a28d5278fedfe14cca697350.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=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 10:44: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:'8124845dd96616f0',t:'MTY5NjY2NDY0Ny40NDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u043d\u043c", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*1800"]
1214A
1214
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.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$$$ рублей. Андрей хочет обменять их на купюры долларов или евро в любой комбинации (то есть, можно покупать одновременно и доллары, и евро). За один доллар придется отдать $$$d$$$ рублей, а за один евро — $$$e$$$ рублей.</p><p>Напомним, что долларовые купюры имеют номиналы $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, а купюры евро — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (купюры номиналом в $$$500$$$ евро в задаче <span class="tex-font-style-bf">отсутствуют</span>, их тяжело найти в обменниках). Андрей может купить любой набор любых купюр. Он хочет сделать так, чтобы рублей у него осталось как можно меньше.</p><p>Помогите ему это сделать — напишите программу, которая по значениям $$$n$$$, $$$e$$$ и $$$d$$$ определит, какое минимальное число рублей может остаться у Андрея после оптимального обмена валюты.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных находится целое число $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — количество рублей у Андрея. </p><p>Во второй строке находится целое число $$$d$$$ ($$$30 \leq d \leq 100$$$) — стоимость одного доллара в рублях. </p><p>В третьей строке находится целое число $$$e$$$ ($$$30 \leq e \leq 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> 100 60 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 410 55 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 600 60 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно купить только $$$1$$$ доллар, потому что купюры в $$$1$$$ евро не существует.</p><p>Во втором примере оптимально купить $$$5$$$ евро и $$$1$$$ доллар.</p><p>В третьем примере можно купить одну $$$10$$$-долларовую купюру.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="d52de1955cedc48d227d8ad6fd9b4201"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='d52de1955cedc48d227d8ad6fd9b4201'>&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%2F1214%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='d52de1955cedc48d227d8ad6fd9b4201'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='d52de1955cedc48d227d8ad6fd9b4201'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='d52de1955cedc48d227d8ad6fd9b4201'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403804"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='d52de1955cedc48d227d8ad6fd9b4201'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403804"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e92e97067ce0733be5c2e25b98b3f8211edb15c9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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.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$$$ рублей. Андрей хочет обменять их на купюры долларов или евро в любой комбинации (то есть, можно покупать одновременно и доллары, и евро). За один доллар придется отдать $$$d$$$ рублей, а за один евро — $$$e$$$ рублей.</p><p>Напомним, что долларовые купюры имеют номиналы $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, а купюры евро — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (купюры номиналом в $$$500$$$ евро в задаче <span class="tex-font-style-bf">отсутствуют</span>, их тяжело найти в обменниках). Андрей может купить любой набор любых купюр. Он хочет сделать так, чтобы рублей у него осталось как можно меньше.</p><p>Помогите ему это сделать — напишите программу, которая по значениям $$$n$$$, $$$e$$$ и $$$d$$$ определит, какое минимальное число рублей может остаться у Андрея после оптимального обмена валюты.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных находится целое число $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — количество рублей у Андрея. </p><p>Во второй строке находится целое число $$$d$$$ ($$$30 \leq d \leq 100$$$) — стоимость одного доллара в рублях. </p><p>В третьей строке находится целое число $$$e$$$ ($$$30 \leq e \leq 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> 100 60 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 40 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 410 55 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 600 60 70 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере можно купить только $$$1$$$ доллар, потому что купюры в $$$1$$$ евро не существует.</p><p>Во втором примере оптимально купить $$$5$$$ евро и $$$1$$$ доллар.</p><p>В третьем примере можно купить одну $$$10$$$-долларовую купюру.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=A]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'812484662f5f9d3f',t:'MTY5NjY2NDY1Mi4xMTgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1400"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214B
1214
B
ru
B. Бейджи
<div class="problem-statement"><div class="header"><div class="title">B. Бейджи</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>На Олимпиаду Мегаполисов приехали $$$b$$$ мальчиков и $$$g$$$ девочек. Известно, что $$$n$$$ из них согласились принять участие в турнире по настольным играм. Организаторы не знают сколько именно среди них мальчиков и девочек.</p><p>Для того чтобы знакомство прошло быстрее, организаторы решили приготовить бейджи: красные для девочек и синие для мальчиков.</p><p>Вася приготовил $$$n+1$$$ колоду с бейджами. В $$$i$$$-й (где $$$i$$$ от $$$0$$$ до $$$n$$$, включительно) колоде у Васи $$$i$$$ синих бейджей и $$$n-i$$$ красных. Суммарное количество бейджей в любой колоде равно $$$n$$$.</p><p>Определите, сколько <span class="tex-font-style-bf">минимум</span> колод из этих $$$n+1$$$ Вася должен взять на турнир, чтобы вне зависимости от количества мальчиков и девочек среди них, нашлась подходящая стопка.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$b$$$ ($$$1 \le b \le 300$$$) — количество мальчиков, которые приехали на олимпиаду.</p><p>Во второй строке находится целое число $$$g$$$ ($$$1 \le g \le 300$$$) — количество девочек, которые приехали на олимпиаду.</p><p>В третьей строке находится целое число $$$n$$$ ($$$1 \le n \le b + g$$$) — количество участников в турнире.</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 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все 4 колоды должны быть использованы: (0 синих, 3 красных), (1 синий, 2 красных), (2 синих, 1 красный), (3 синих, 0 красных).</p><p>Во втором примере 4 колоды должны быть использованы: (2 синих, 3 красных), (3 синих, 2 красных), (4 синих, 1 красный), (5 синих, 0 красных). Стопки (0 синих, 5 красных) и (1 синий, 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="5e95dc132a00678eb58df7a8acf28413"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='5e95dc132a00678eb58df7a8acf28413'>&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%2F1214%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='5e95dc132a00678eb58df7a8acf28413'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='5e95dc132a00678eb58df7a8acf28413'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='5e95dc132a00678eb58df7a8acf28413'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403805"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5e95dc132a00678eb58df7a8acf28413'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403805"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_9a512af5cdcc6daddabda28fb8f178bbcc00e358"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>На Олимпиаду Мегаполисов приехали $$$b$$$ мальчиков и $$$g$$$ девочек. Известно, что $$$n$$$ из них согласились принять участие в турнире по настольным играм. Организаторы не знают сколько именно среди них мальчиков и девочек.</p><p>Для того чтобы знакомство прошло быстрее, организаторы решили приготовить бейджи: красные для девочек и синие для мальчиков.</p><p>Вася приготовил $$$n+1$$$ колоду с бейджами. В $$$i$$$-й (где $$$i$$$ от $$$0$$$ до $$$n$$$, включительно) колоде у Васи $$$i$$$ синих бейджей и $$$n-i$$$ красных. Суммарное количество бейджей в любой колоде равно $$$n$$$.</p><p>Определите, сколько <span class="tex-font-style-bf">минимум</span> колод из этих $$$n+1$$$ Вася должен взять на турнир, чтобы вне зависимости от количества мальчиков и девочек среди них, нашлась подходящая стопка.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находится целое число $$$b$$$ ($$$1 \le b \le 300$$$) — количество мальчиков, которые приехали на олимпиаду.</p><p>Во второй строке находится целое число $$$g$$$ ($$$1 \le g \le 300$$$) — количество девочек, которые приехали на олимпиаду.</p><p>В третьей строке находится целое число $$$n$$$ ($$$1 \le n \le b + g$$$) — количество участников в турнире.</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 6 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере все 4 колоды должны быть использованы: (0 синих, 3 красных), (1 синий, 2 красных), (2 синих, 1 красный), (3 синих, 0 красных).</p><p>Во втором примере 4 колоды должны быть использованы: (2 синих, 3 красных), (3 синих, 2 красных), (4 синих, 1 красный), (5 синих, 0 красных). Стопки (0 синих, 5 красных) и (1 синий, 4 красных) не могут понадобиться.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=B]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44:13</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:'812484838ad71697',t:'MTY5NjY2NDY1My41MDAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1100"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214C
1214
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>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>Чтобы исправить последовательность Петя собирается не более одного раза взять произвольную скобку и вынуть её из последовательности (при этом оставшиеся скобки сдвигаются), после чего вставить её обратно в произвольное место в последовательности. Разворачивать скобку при этом не разрешается.</p><p>Напомним, что последовательность $$$s$$$ из круглых скобок называется правильной, если: </p><ul> <li> $$$s$$$ является пустой; </li><li> $$$s$$$ равна «<span class="tex-font-style-tt">(</span>$$$t$$$<span class="tex-font-style-tt">)</span>», где $$$t$$$ — правильная скобочная последовательность; </li><li> $$$s$$$ равна $$$t_1 t_2$$$, то есть конкатенации $$$t_1$$$ и $$$t_2$$$, где $$$t_1$$$ и $$$t_2$$$ являются правильными скобочными последовательностями. </li></ul><p>Например, последовательности «<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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано единственное число $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — длина последовательности, которую друзья подарили Пете.</p><p>Во второй строке входных данных записана строка длины $$$n$$$, состоящая из символов «<span class="tex-font-style-tt">(</span>)» и «<span class="tex-font-style-tt">)</span>».</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<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 )( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 (() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 () </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 )))))((((( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Петя может переставить первую скобку в конец, тогда получится строка «<span class="tex-font-style-tt">()</span>», которая является правильной скобочной последовательностью.</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="a287528baa62f7bce4395c49f90568a0"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='a287528baa62f7bce4395c49f90568a0'>&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%2F1214%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='a287528baa62f7bce4395c49f90568a0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='a287528baa62f7bce4395c49f90568a0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='a287528baa62f7bce4395c49f90568a0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403806"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a287528baa62f7bce4395c49f90568a0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403806"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f850241d832ec8bfc4bd44c4d3c567099b8a1d39"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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>Чтобы исправить последовательность Петя собирается не более одного раза взять произвольную скобку и вынуть её из последовательности (при этом оставшиеся скобки сдвигаются), после чего вставить её обратно в произвольное место в последовательности. Разворачивать скобку при этом не разрешается.</p><p>Напомним, что последовательность $$$s$$$ из круглых скобок называется правильной, если: </p><ul> <li> $$$s$$$ является пустой; </li><li> $$$s$$$ равна «<span class="tex-font-style-tt">(</span>$$$t$$$<span class="tex-font-style-tt">)</span>», где $$$t$$$ — правильная скобочная последовательность; </li><li> $$$s$$$ равна $$$t_1 t_2$$$, то есть конкатенации $$$t_1$$$ и $$$t_2$$$, где $$$t_1$$$ и $$$t_2$$$ являются правильными скобочными последовательностями. </li></ul><p>Например, последовательности «<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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке входных данных записано единственное число $$$n$$$ ($$$1 \leq n \leq 200\,000$$$) — длина последовательности, которую друзья подарили Пете.</p><p>Во второй строке входных данных записана строка длины $$$n$$$, состоящая из символов «<span class="tex-font-style-tt">(</span>)» и «<span class="tex-font-style-tt">)</span>».</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<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 )( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 (() </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 () </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 )))))((((( </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Петя может переставить первую скобку в конец, тогда получится строка «<span class="tex-font-style-tt">()</span>», которая является правильной скобочной последовательностью.</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 10:44: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:'8124848c0a1f0058',t:'MTY5NjY2NDY1NC44NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1200"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214D
1214
D
ru
D. Остров Сокровищ
<div class="problem-statement"><div class="header"><div class="title">D. Остров Сокровищ</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Сокровища! Кто не мечтал о них в детстве? Именно так подумал юный Вася и отправился в длительное путешествие к Острову Сокровищ.</p><p>Остров Сокровищ представляет собой прямоугольное поле $$$n \times m$$$, окруженное океаном. Пронумеруем строки поля последовательными целыми числами от $$$1$$$ до $$$n$$$ сверху вниз, а столбцы последовательными целыми числами от $$$1$$$ до $$$m$$$ слева направо. Обозначение $$$(r, c)$$$ соответствует клетке, расположенной в строке $$$r$$$ и столбце $$$c$$$. В некоторых клетках острова растут непроходимые леса, а остальные клетки свободные и проходимые. Сокровище закопано в клетке $$$(n, m)$$$.</p><p>Вася высадился с корабля в клетку $$$(1, 1)$$$. Теперь он хочет добраться до сокровища. Вася сильно спешит за сокровищем, поэтому может перемещаться только в клетку в следующей строке (вниз) или следующем столбце (вправо), то есть из клетки $$$(x, y)$$$ он может сделать ход только в клетки $$$(x+1, y)$$$ и $$$(x, y+1)$$$. Конечно, Вася не может заходить в клетки, где растёт непроходимый лес.</p><p>Злая Ведьма узнала о планах Васи завладеть сокровищами и хочет ему помешать. До начала движения Васи она с помощью своей магии может вырастить непроходимые леса в клетках, которые ранее были свободными. Ведьма может вырастить непроходимый лес в любых клетках, кроме клетки $$$(1, 1)$$$, где уже высадился Вася, и клетки $$$(n, m)$$$, где закопаны сокровища.</p><p>Помогите Злой Ведьме определить, на каком минимальном количестве клеток ей придётся вырастить непроходимый лес, чтобы Вася не смог добраться до сокровища?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых положительных числа $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$) — размеры острова.</p><p>Следующие $$$n$$$ строк содержат строки $$$s_i$$$ длины $$$m$$$, задающие описание острова, $$$j$$$-й символ строки $$$s_i$$$ равен «<span class="tex-font-style-tt">#</span>», если в клетке $$$(i, j)$$$ острова растёт непроходимый лес и «<span class="tex-font-style-tt">.</span>», если клетка свободна. Напомним, что Вася высаживается в клетке $$$(1, 1)$$$, то есть в первой клетке первой строки и идёт навстречу сокровищам, находящимся в клетке $$$(n, m)$$$, то есть в последней клетке последней строки.</p><p>гарантируется, что клетки $$$(1, 1)$$$ и $$$(n, m)$$$ не содержат леса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число $$$k$$$  — минимальное количестве клеток, в которых Злой Ведьме нужно вырастить непроходимый лес, чтобы Вася не смог добраться до сокровища.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 .. .. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 .... #.#. .... .#.. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 .... .##. .... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая картинка изображает осторов в третьем примере. Синим отмечены возможные пути Васи из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$, красным отмечены клетки, на которых ведьма может вырастить непроходимый лес, чтобы Вася не смог добраться из $$$(1, 1)$$$ в $$$(n, m)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f839329c1409162b4e6d427a20daa8442670c84e.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="a59b7c8b5a7cb59aca8cb74dd231b66c"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='a59b7c8b5a7cb59aca8cb74dd231b66c'>&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%2F1214%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='a59b7c8b5a7cb59aca8cb74dd231b66c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='a59b7c8b5a7cb59aca8cb74dd231b66c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='a59b7c8b5a7cb59aca8cb74dd231b66c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403807"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='a59b7c8b5a7cb59aca8cb74dd231b66c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403807"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e81f0abcb1af63d4b19b715d805b98be884eda21"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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 m$$$, окруженное океаном. Пронумеруем строки поля последовательными целыми числами от $$$1$$$ до $$$n$$$ сверху вниз, а столбцы последовательными целыми числами от $$$1$$$ до $$$m$$$ слева направо. Обозначение $$$(r, c)$$$ соответствует клетке, расположенной в строке $$$r$$$ и столбце $$$c$$$. В некоторых клетках острова растут непроходимые леса, а остальные клетки свободные и проходимые. Сокровище закопано в клетке $$$(n, m)$$$.</p><p>Вася высадился с корабля в клетку $$$(1, 1)$$$. Теперь он хочет добраться до сокровища. Вася сильно спешит за сокровищем, поэтому может перемещаться только в клетку в следующей строке (вниз) или следующем столбце (вправо), то есть из клетки $$$(x, y)$$$ он может сделать ход только в клетки $$$(x+1, y)$$$ и $$$(x, y+1)$$$. Конечно, Вася не может заходить в клетки, где растёт непроходимый лес.</p><p>Злая Ведьма узнала о планах Васи завладеть сокровищами и хочет ему помешать. До начала движения Васи она с помощью своей магии может вырастить непроходимые леса в клетках, которые ранее были свободными. Ведьма может вырастить непроходимый лес в любых клетках, кроме клетки $$$(1, 1)$$$, где уже высадился Вася, и клетки $$$(n, m)$$$, где закопаны сокровища.</p><p>Помогите Злой Ведьме определить, на каком минимальном количестве клеток ей придётся вырастить непроходимый лес, чтобы Вася не смог добраться до сокровища?</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых положительных числа $$$n$$$, $$$m$$$ ($$$3 \le n \cdot m \le 1\,000\,000$$$) — размеры острова.</p><p>Следующие $$$n$$$ строк содержат строки $$$s_i$$$ длины $$$m$$$, задающие описание острова, $$$j$$$-й символ строки $$$s_i$$$ равен «<span class="tex-font-style-tt">#</span>», если в клетке $$$(i, j)$$$ острова растёт непроходимый лес и «<span class="tex-font-style-tt">.</span>», если клетка свободна. Напомним, что Вася высаживается в клетке $$$(1, 1)$$$, то есть в первой клетке первой строки и идёт навстречу сокровищам, находящимся в клетке $$$(n, m)$$$, то есть в последней клетке последней строки.</p><p>гарантируется, что клетки $$$(1, 1)$$$ и $$$(n, m)$$$ не содержат леса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число $$$k$$$  — минимальное количестве клеток, в которых Злой Ведьме нужно вырастить непроходимый лес, чтобы Вася не смог добраться до сокровища.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 .. .. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 .... #.#. .... .#.. </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 4 .... .##. .... </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Следующая картинка изображает осторов в третьем примере. Синим отмечены возможные пути Васи из клетки $$$(1, 1)$$$ в клетку $$$(n, m)$$$, красным отмечены клетки, на которых ведьма может вырастить непроходимый лес, чтобы Вася не смог добраться из $$$(1, 1)$$$ в $$$(n, m)$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/f839329c1409162b4e6d427a20daa8442670c84e.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 10:44: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:'812484946e449d70',t:'MTY5NjY2NDY1Ni4xODQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0442\u043e\u043a\u0438 \u0432 \u0433\u0440\u0430\u0444\u0430\u0445", "\u0425\u044d\u0448\u0438, \u0445\u044d\u0448-\u0442\u0430\u0431\u043b\u0438\u0446\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u043f\u043e\u0442\u043e\u043a\u0438", "\u0445\u044d\u0448\u0438", "*1900"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214E
1214
E
ru
E. Петя и конструктор
<div class="problem-statement"><div class="header"><div class="title">E. Петя и конструктор</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Недавно у Пети был день рождения. Его друзья знают, что Петя очень сильно любит головоломки, поэтому они подарили ему популярный конструктор «Электрик-$$$n$$$». </p><p>Конструктор «Электрик-$$$n$$$» состоит из $$$2n - 1$$$ проводов и $$$2n$$$ лампочек. При этом каждая лампочка имеет свой уникальный номер, являющийся целыми числом от $$$1$$$ до $$$2n$$$, а все провода являются одинаковыми и неразличимы. Чтобы собрать конструктор требуется каждый из проводов использовать для соединения каких-то двух различных лампочек. <span class="tex-font-style-it">Цепочкой</span> в собранном конструкторе назовём последовательность из не менее чем двух различных лампочек, такую что любые две соседние в цепочке лампочки соединены проводом напрямую. Итоговая конфигурация конструктора является корректной, если сеть из проводов и лампочек имеет древовидную структуру, то есть любые две различные лампочки являются концами какой-нибудь цепочки.</p><p>На протяжении нескольких дней Петя собирал различные конфигурации. Он обратил внимание на то, что иногда некоторые лампочки начинают светиться. После продолжительных экспериментов Петя выяснил, что лампочки с номерами $$$2i$$$ и $$$2i - 1$$$ горят тогда, когда цепочка между ними состоит ровно из $$$d_i$$$ проводов. При этом выполнялось <span class="tex-font-style-bf">важное</span> условие: значение $$$d_i$$$ всегда было не больше $$$n$$$.</p><p>Сколько бы Петя не старался, у него так и не получилось найти конфигурацию, в которой бы светились все лампочки, поэтому он решил попросить помощи у вас. Требуется найти любую корректную конфигурацию, в которой горят все лампочки. Гарантируется, что это всегда возможно сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — параметр конструктора, определяющий количество лампочек и количество проводов.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$ ($$$1 \leq d_i \leq n$$$), где $$$d_i$$$ — требуемое число проводов в цепочке, чтобы лампочки $$$2i$$$ и $$$2i - 1$$$ светились.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2n - 1$$$ строк. В $$$i$$$-й строке должны быть записаны два различных целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 2n$$$, $$$a_i \ne b_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> 3 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 2 6 3 5 3 6 4 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 1 7 2 6 3 5 3 6 4 5 7 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 2 2 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 2 3 3 5 4 5 5 7 6 7 7 12 8 12 9 11 9 12 10 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 4 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" height="151px" src="https://espresso.codeforces.com/27a758093031f9327df8cc7d0df52dfec727e664.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> </center> <center> Ответ на первый тест из условия. </center> <center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/7860714083483e8556d4431d868dd02b60558c36.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px"/> </center> <center> Ответ на второй тест из условия. </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="39580e8a3b5c936e0b17dea3a86257e9"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='39580e8a3b5c936e0b17dea3a86257e9'>&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%2F1214%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='39580e8a3b5c936e0b17dea3a86257e9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='39580e8a3b5c936e0b17dea3a86257e9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='39580e8a3b5c936e0b17dea3a86257e9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403808"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='39580e8a3b5c936e0b17dea3a86257e9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403808"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8fecf48fbf36ff32b2f4969f83aff55e334650cd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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$$$». </p><p>Конструктор «Электрик-$$$n$$$» состоит из $$$2n - 1$$$ проводов и $$$2n$$$ лампочек. При этом каждая лампочка имеет свой уникальный номер, являющийся целыми числом от $$$1$$$ до $$$2n$$$, а все провода являются одинаковыми и неразличимы. Чтобы собрать конструктор требуется каждый из проводов использовать для соединения каких-то двух различных лампочек. <span class="tex-font-style-it">Цепочкой</span> в собранном конструкторе назовём последовательность из не менее чем двух различных лампочек, такую что любые две соседние в цепочке лампочки соединены проводом напрямую. Итоговая конфигурация конструктора является корректной, если сеть из проводов и лампочек имеет древовидную структуру, то есть любые две различные лампочки являются концами какой-нибудь цепочки.</p><p>На протяжении нескольких дней Петя собирал различные конфигурации. Он обратил внимание на то, что иногда некоторые лампочки начинают светиться. После продолжительных экспериментов Петя выяснил, что лампочки с номерами $$$2i$$$ и $$$2i - 1$$$ горят тогда, когда цепочка между ними состоит ровно из $$$d_i$$$ проводов. При этом выполнялось <span class="tex-font-style-bf">важное</span> условие: значение $$$d_i$$$ всегда было не больше $$$n$$$.</p><p>Сколько бы Петя не старался, у него так и не получилось найти конфигурацию, в которой бы светились все лампочки, поэтому он решил попросить помощи у вас. Требуется найти любую корректную конфигурацию, в которой горят все лампочки. Гарантируется, что это всегда возможно сделать.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — параметр конструктора, определяющий количество лампочек и количество проводов.</p><p>В следующей строке записаны $$$n$$$ целых чисел $$$d_1, d_2, \ldots, d_n$$$ ($$$1 \leq d_i \leq n$$$), где $$$d_i$$$ — требуемое число проводов в цепочке, чтобы лампочки $$$2i$$$ и $$$2i - 1$$$ светились.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$2n - 1$$$ строк. В $$$i$$$-й строке должны быть записаны два различных целых числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \leq a_i, b_i \leq 2n$$$, $$$a_i \ne b_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> 3 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 2 6 3 5 3 6 4 5 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2 2 2 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 6 1 7 2 6 3 5 3 6 4 5 7 8 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 2 2 2 2 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 2 3 3 5 4 5 5 7 6 7 7 12 8 12 9 11 9 12 10 11 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 1 4 3 4 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><center> <img class="tex-graphics" height="151px" src="https://espresso.codeforces.com/27a758093031f9327df8cc7d0df52dfec727e664.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> </center> <center> Ответ на первый тест из условия. </center> <center> <img class="tex-graphics" height="302px" src="https://espresso.codeforces.com/7860714083483e8556d4431d868dd02b60558c36.png" style="max-width: 100.0%;max-height: 100.0%;" width="302px" /> </center> <center> Ответ на второй тест из условия. </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 10:44: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:'8124849cdf8b7b83',t:'MTY5NjY2NDY1Ny40OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\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", "*2000"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214F
1214
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>В мире давно происходит противостояние двух крупных компаний: «Cecsi» и «Poca Pola». Чтобы окончательно покончить со своим конкурентом, компания «Poca Pola» занялась сверхсекретным проектом, для которого в разных офисах им потребовалось суммарно $$$n$$$ новых сторудников. После череды отборов, тестирований и собеседований было выбрано $$$n$$$ подходящих кандидатов, и дело осталось за малым — их трудоустройством.</p><p>Так как все кандидаты имеют одинаковые навыки и умения, абсолютно неважно, на какое именно рабочее место отправить каждого из них. Поэтому руководство компании «Poca Pola» решило распределить кандидатов между рабочими местами так, чтобы суммарное расстояние от дома кандидата до места его работы было бы минимально.</p><p>Как известно, Земля круглая, поэтому весь мир представляется окружностью, на некоторых точках которой стоит суммарно $$$m$$$ городов. Все города пронумерованы по часовой стрелке целыми числами от $$$1$$$ до $$$m$$$ так, что для любого $$$i$$$ ($$$1 \le i \le m - 1$$$) города с номерами $$$i$$$ и $$$i + 1$$$ соседние, также соседними являются города $$$1$$$ и $$$m$$$. Перемещаться между городами можно только по поверхности Земли, причём из города можно перейти только в один из двух соседних с ним. Расстояние между двумя городами равно минимальному числу переходов из города в соседний, которое нужно совершить, чтобы добраться от одного города до другого. В частности, расстояние между городом и им же самим равно $$$0$$$.</p><p>Известно, что рабочие места компании «Poca Pola» находятся в городах $$$a_1, a_2, \ldots, a_n$$$. Также для каждого кандидата известны города их жительства — $$$b_1, b_2, \ldots, b_n$$$. Возможно, что несколько рабочих мест находятся в одном городе, а также возможно, что несколько людей живут в одном городе.</p><p>Руководство компании «Poca Pola» слишком занято сверхсекретным проектом, поэтому вам было поручено распределить кандидатов по рабочим местам так, чтобы суммарное расстояние для всех кандидатов от города проживания до города, где он работает, было бы минимальным возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$m$$$ и $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 200\,000$$$) — количество городов на Земле и количество рабочих мест соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, a_3, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — города, в которых находятся рабочие места.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, b_3, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — города, в которых живут кандидаты.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите минимальное суммарное расстояние от кандидатов до назначенных им мест работы.</p><p>Во второй строке выведите $$$n$$$ различный целых чисел от $$$1$$$ до $$$n$$$, где $$$i$$$-е из них равно номеру кандидата, которого надо отправить на $$$i$$$-е рабочее место. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 3 1 5 5 10 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 3 1 4 8 8 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 2 3 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, расстояние от каждого кандидата до его работы равно $$$1$$$ (от $$$10$$$ до $$$1$$$, от $$$4$$$ до $$$5$$$ и от $$$6$$$ до $$$5$$$).</p><p>Во втором примере:</p><ul> <li> На первую работу назначен второй кандидат, расстояние от $$$3$$$-го города до $$$1$$$ равно $$$2$$$. </li><li> На вторую работу назначен третий кандидат, расстояние от $$$6$$$-го города до $$$4$$$ равно $$$2$$$. </li><li> На третью работу назначен первый кандидат, расстояние от $$$8$$$-го города до $$$8$$$ равно $$$0$$$. </li></ul> </div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="2a8c6255e827020b12860fd5cb01cfbb"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='2a8c6255e827020b12860fd5cb01cfbb'>&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%2F1214%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='2a8c6255e827020b12860fd5cb01cfbb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='2a8c6255e827020b12860fd5cb01cfbb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='2a8c6255e827020b12860fd5cb01cfbb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403809"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2a8c6255e827020b12860fd5cb01cfbb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403809"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_116e4c04a8412b29182e82f1dd0deb3868b6c8af"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>В мире давно происходит противостояние двух крупных компаний: «Cecsi» и «Poca Pola». Чтобы окончательно покончить со своим конкурентом, компания «Poca Pola» занялась сверхсекретным проектом, для которого в разных офисах им потребовалось суммарно $$$n$$$ новых сторудников. После череды отборов, тестирований и собеседований было выбрано $$$n$$$ подходящих кандидатов, и дело осталось за малым — их трудоустройством.</p><p>Так как все кандидаты имеют одинаковые навыки и умения, абсолютно неважно, на какое именно рабочее место отправить каждого из них. Поэтому руководство компании «Poca Pola» решило распределить кандидатов между рабочими местами так, чтобы суммарное расстояние от дома кандидата до места его работы было бы минимально.</p><p>Как известно, Земля круглая, поэтому весь мир представляется окружностью, на некоторых точках которой стоит суммарно $$$m$$$ городов. Все города пронумерованы по часовой стрелке целыми числами от $$$1$$$ до $$$m$$$ так, что для любого $$$i$$$ ($$$1 \le i \le m - 1$$$) города с номерами $$$i$$$ и $$$i + 1$$$ соседние, также соседними являются города $$$1$$$ и $$$m$$$. Перемещаться между городами можно только по поверхности Земли, причём из города можно перейти только в один из двух соседних с ним. Расстояние между двумя городами равно минимальному числу переходов из города в соседний, которое нужно совершить, чтобы добраться от одного города до другого. В частности, расстояние между городом и им же самим равно $$$0$$$.</p><p>Известно, что рабочие места компании «Poca Pola» находятся в городах $$$a_1, a_2, \ldots, a_n$$$. Также для каждого кандидата известны города их жительства — $$$b_1, b_2, \ldots, b_n$$$. Возможно, что несколько рабочих мест находятся в одном городе, а также возможно, что несколько людей живут в одном городе.</p><p>Руководство компании «Poca Pola» слишком занято сверхсекретным проектом, поэтому вам было поручено распределить кандидатов по рабочим местам так, чтобы суммарное расстояние для всех кандидатов от города проживания до города, где он работает, было бы минимальным возможным.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$m$$$ и $$$n$$$ ($$$1 \le m \le 10^9$$$, $$$1 \le n \le 200\,000$$$) — количество городов на Земле и количество рабочих мест соответственно.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, a_3, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — города, в которых находятся рабочие места.</p><p>Третья строка содержит $$$n$$$ целых чисел $$$b_1, b_2, b_3, \ldots, b_n$$$ ($$$1 \le b_i \le m$$$) — города, в которых живут кандидаты.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите минимальное суммарное расстояние от кандидатов до назначенных им мест работы.</p><p>Во второй строке выведите $$$n$$$ различный целых чисел от $$$1$$$ до $$$n$$$, где $$$i$$$-е из них равно номеру кандидата, которого надо отправить на $$$i$$$-е рабочее место. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 10 3 1 5 5 10 4 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 3 1 4 8 8 3 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 2 3 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере, расстояние от каждого кандидата до его работы равно $$$1$$$ (от $$$10$$$ до $$$1$$$, от $$$4$$$ до $$$5$$$ и от $$$6$$$ до $$$5$$$).</p><p>Во втором примере:</p><ul> <li> На первую работу назначен второй кандидат, расстояние от $$$3$$$-го города до $$$1$$$ равно $$$2$$$. </li><li> На вторую работу назначен третий кандидат, расстояние от $$$6$$$-го города до $$$4$$$ равно $$$2$$$. </li><li> На третью работу назначен первый кандидат, расстояние от $$$8$$$-го города до $$$8$$$ равно $$$0$$$. </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 10:44: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:'812484a51fec9d96',t:'MTY5NjY2NDY1OC44NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*2700"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214G
1214
G
ru
G. Хорошее настроение
<div class="problem-statement"><div class="header"><div class="title">G. Хорошее настроение</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>512 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Недавно биологами было сделано удивительное открытие, позволяющее определять в каком настроении находится хамелеон. Для простоты будем считать, что туловище хамелеона имеет вид таблицы размером $$$n \times m$$$, каждая клетка которой может быть зеленой или синей и изменять свой цвет. Будем обозначать за $$$(x, y)$$$ ($$$1 \leq x \leq n$$$, $$$1 \leq y \leq m$$$) клетку, которая находится в строке с номером $$$x$$$ и столбце с номером $$$y$$$.</p><p>Будем называть <span class="tex-font-style-it">признаком хорошего настроения</span> хамелеона такую четверку клеток, являющихся угловыми клетками некоторого прямоугольника внутри таблицы, что цвета клеток в противоположных углах совпадают, но при этом не все четыре клетки одного цвета. Более формально, это четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ для некоторых $$$1 \leq x_1 &lt; x_2 \leq n$$$, $$$1 \leq y_1 &lt; y_2 \leq m$$$, что цвета $$$(x_1, y_1)$$$ и $$$(x_2, y_2)$$$ совпадают и цвета $$$(x_1, y_2)$$$ и $$$(x_2, y_1)$$$ совпадают, но при этом не все четыре клетки имеют одинаковый цвет. Было обнаружено, что если такая четверка клеток существует, то у хамелеона хорошее настроение; в противном случае настроение хамелеона плохое.</p><p>Вас просят помочь учёным написать программу, которая определяет настроение хамелеона. Будем считать, что изначально хамелеон полностью зеленый, то есть все клетки таблицы имеют зеленый цвет. После этого окраска хамелеона может несколько раз измениться. За один раз цвет клеток некоторого отрезка одной строки таблицы может измениться на противоположный. Более формально, каждое изменение окраски хамелеона задается числами $$$a$$$, $$$l$$$, $$$r$$$ ($$$1 \leq a \leq n$$$, $$$1 \leq l \leq r \leq m$$$). При этом цвет всех клеток $$$(a, b)$$$, таких, что $$$l \leq b \leq r$$$, меняется на противоположный.</p><p>Напишите программу, которая после каждого изменения окраски будет сообщать настроение хамелеона. При этом, если настроение хамелеона хорошее, то программа должна сообщать любые подходящие $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$, такие, что четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ является признаком хорошего настроения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \leq n, m \leq 2000$$$, $$$1 \leq q \leq 500\,000$$$) — размеры таблицы и количество изменений окраски хамелеона. </p><p>В следующих $$$q$$$ строках находятся по 3 целых числа $$$a_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1 \leq a_i \leq n$$$, $$$1 \leq l_i \leq r_i \leq m$$$) — описание $$$i$$$-го по порядку изменения окраски хамелеона.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$ строке выведите описание настроения хамелеона после первых $$$i$$$ изменений окраски для всех $$$1 \leq i \leq q$$$. </p><p>Если настроение хамелеона плохое, то выведите единственное число $$$-1$$$. </p><p>Иначе выведите четыре целых числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1 &lt; x_2 \leq n$$$, $$$1 \leq y_1 &lt; y_2 \leq m$$$), таких что четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ является признаком хорошего настроения хамелеона. Если возможных четвёрок несколько, разрешается вывести любую из них.</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 6 1 1 1 2 2 2 2 1 1 1 2 2 2 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 1 1 2 2 -1 -1 -1 1 1 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 9 2 2 3 4 1 2 2 1 3 3 2 2 3 1 3 1 2 2 4 2 3 1 1 3 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 2 1 4 3 -1 2 1 3 2 3 2 4 3 1 1 2 2 1 1 2 2 -1 2 1 3 2 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="adb76ea6ff650e24041acb344433c173"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='adb76ea6ff650e24041acb344433c173'>&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%2F1214%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='adb76ea6ff650e24041acb344433c173'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='adb76ea6ff650e24041acb344433c173'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='adb76ea6ff650e24041acb344433c173'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403810"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='adb76ea6ff650e24041acb344433c173'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403810"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_45ed3013106d83a9f5aa7ebda892a7c872a528bd"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>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$$$, каждая клетка которой может быть зеленой или синей и изменять свой цвет. Будем обозначать за $$$(x, y)$$$ ($$$1 \leq x \leq n$$$, $$$1 \leq y \leq m$$$) клетку, которая находится в строке с номером $$$x$$$ и столбце с номером $$$y$$$.</p><p>Будем называть <span class="tex-font-style-it">признаком хорошего настроения</span> хамелеона такую четверку клеток, являющихся угловыми клетками некоторого прямоугольника внутри таблицы, что цвета клеток в противоположных углах совпадают, но при этом не все четыре клетки одного цвета. Более формально, это четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ для некоторых $$$1 \leq x_1 &lt; x_2 \leq n$$$, $$$1 \leq y_1 &lt; y_2 \leq m$$$, что цвета $$$(x_1, y_1)$$$ и $$$(x_2, y_2)$$$ совпадают и цвета $$$(x_1, y_2)$$$ и $$$(x_2, y_1)$$$ совпадают, но при этом не все четыре клетки имеют одинаковый цвет. Было обнаружено, что если такая четверка клеток существует, то у хамелеона хорошее настроение; в противном случае настроение хамелеона плохое.</p><p>Вас просят помочь учёным написать программу, которая определяет настроение хамелеона. Будем считать, что изначально хамелеон полностью зеленый, то есть все клетки таблицы имеют зеленый цвет. После этого окраска хамелеона может несколько раз измениться. За один раз цвет клеток некоторого отрезка одной строки таблицы может измениться на противоположный. Более формально, каждое изменение окраски хамелеона задается числами $$$a$$$, $$$l$$$, $$$r$$$ ($$$1 \leq a \leq n$$$, $$$1 \leq l \leq r \leq m$$$). При этом цвет всех клеток $$$(a, b)$$$, таких, что $$$l \leq b \leq r$$$, меняется на противоположный.</p><p>Напишите программу, которая после каждого изменения окраски будет сообщать настроение хамелеона. При этом, если настроение хамелеона хорошее, то программа должна сообщать любые подходящие $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$, такие, что четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ является признаком хорошего настроения.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке находятся три целых числа $$$n$$$, $$$m$$$, $$$q$$$ ($$$1 \leq n, m \leq 2000$$$, $$$1 \leq q \leq 500\,000$$$) — размеры таблицы и количество изменений окраски хамелеона. </p><p>В следующих $$$q$$$ строках находятся по 3 целых числа $$$a_i$$$, $$$l_i$$$, $$$r_i$$$ ($$$1 \leq a_i \leq n$$$, $$$1 \leq l_i \leq r_i \leq m$$$) — описание $$$i$$$-го по порядку изменения окраски хамелеона.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$ строке выведите описание настроения хамелеона после первых $$$i$$$ изменений окраски для всех $$$1 \leq i \leq q$$$. </p><p>Если настроение хамелеона плохое, то выведите единственное число $$$-1$$$. </p><p>Иначе выведите четыре целых числа $$$x_1$$$, $$$y_1$$$, $$$x_2$$$, $$$y_2$$$ ($$$1 \leq x_1 &lt; x_2 \leq n$$$, $$$1 \leq y_1 &lt; y_2 \leq m$$$), таких что четверка клеток $$$(x_1, y_1)$$$, $$$(x_1, y_2)$$$, $$$(x_2, y_1)$$$, $$$(x_2, y_2)$$$ является признаком хорошего настроения хамелеона. Если возможных четвёрок несколько, разрешается вывести любую из них.</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 6 1 1 1 2 2 2 2 1 1 1 2 2 2 2 2 1 1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 1 1 2 2 -1 -1 -1 1 1 2 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 3 9 2 2 3 4 1 2 2 1 3 3 2 2 3 1 3 1 2 2 4 2 3 1 1 3 3 1 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 2 1 4 3 -1 2 1 3 2 3 2 4 3 1 1 2 2 1 1 2 2 -1 2 1 3 2 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'812484ad7b169da5',t:'MTY5NjY2NDY2MC4yMDcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3200"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1214H
1214
H
ru
H. Укладывание плитки
<div class="problem-statement"><div class="header"><div class="title">H. Укладывание плитки</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$$$ площадей, соединённых друг с другом с помощью $$$n - 1$$$ пешеходных дорожек. <span class="tex-font-style-it">Простым путём</span> называется такая последовательность площадей, что никакая площадь не встречается в последовательности дважды, и любые две соседние в последовательности площади напрямую соединены пешеходной дорожкой. Размером простого пути будем называть количество площадей в образующей его последовательности. Дорожки спроектированы таким образом, что между любой парой различных площадей существует ровно один простой путь.</p><p>В рамках подготовки к празднованию дня города московская мэрия планирует обновить плитку на всех $$$n$$$ площадях. Всего существует $$$k$$$ видов плитки разных цветов, пронумерованных от $$$1$$$ до $$$k$$$. Для каждой площади нужно выбрать ровно один вид плитки, который будет там уложен в процессе обновления. Чтобы сделать прогулки по центру Москвы более увлекательными, было решено назначить типы плиток площадям таким образом, чтобы для любого возможного простого пути размера ровно $$$k$$$, при прогулке вдоль этого пути встречались бы все $$$k$$$ различных типов плитки.</p><p>Определите, можно ли уложить плитку подходящим образом или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$2 \le k \le n \le 200\,000$$$) — количество площадей в Москве, количество различных цветов плитки.</p><p>Каждая из последующих $$$n - 1$$$ строк содержит по два целых числа $$$v_i$$$ и $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$) — номера площадей, соединённых данной пешеходной дорожкой.</p><p>Гарантируется, что от любой площади можно добраться до любой другой, причём единственным способом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если уложить плитку возможно, и «<span class="tex-font-style-tt">No</span>» иначе.</p><p>В случае если ваш ответ «<span class="tex-font-style-tt">Yes</span>», выведите $$$n$$$ целых чисел от $$$1$$$ до $$$k$$$ — цвет плитки для каждой площади.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 4 1 3 2 3 3 4 4 5 5 6 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 1 1 2 3 4 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 1 3 2 3 3 4 4 5 5 6 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображена карта пешеходной зоны из первого и второго примеров, а также корректный выбор типов плитки для $$$k = 4$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6cc7c15dbf9574a390d9ef5ea801eba64888e377.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="4a7637b90bb8bfdf19fed9f6bf16eed7"/> <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="ea4e83fcde094f27a041d0c088125cbec3cf1bde"/> <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='4a7637b90bb8bfdf19fed9f6bf16eed7'>&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%2F1214%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='4a7637b90bb8bfdf19fed9f6bf16eed7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1214">Codeforces Round 583 (Div. 1 + 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='4a7637b90bb8bfdf19fed9f6bf16eed7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1214/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='4a7637b90bb8bfdf19fed9f6bf16eed7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="403811"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4a7637b90bb8bfdf19fed9f6bf16eed7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="403811"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69538" title="Codeforces Round #583 (по задачам Олимпиады Мегаполисов) (div. 1 + div. 2)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9299:9300" 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="https://codeforces.com/blog/entry/69563" title="Tutorial" target="_blank">Tutorial <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9307" 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/1214">Задачи</a></li> <li><a href="/contest/1214/submit">Отослать</a></li> <li><a href="/contest/1214/my">Мои посылки</a></li> <li><a href="/contest/1214/status">Статус</a></li> <li><a href="/contest/1214/hacks">Взломы</a></li> <li><a href="/contest/1214/room/1">Комната</a></li> <li><a href="/contest/1214/standings">Положение</a></li> <li><a href="/contest/1214/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_838d30d18ad7a880f684c3f9dd67df63af530ff0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Укладывание плитки</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$$$ площадей, соединённых друг с другом с помощью $$$n - 1$$$ пешеходных дорожек. <span class="tex-font-style-it">Простым путём</span> называется такая последовательность площадей, что никакая площадь не встречается в последовательности дважды, и любые две соседние в последовательности площади напрямую соединены пешеходной дорожкой. Размером простого пути будем называть количество площадей в образующей его последовательности. Дорожки спроектированы таким образом, что между любой парой различных площадей существует ровно один простой путь.</p><p>В рамках подготовки к празднованию дня города московская мэрия планирует обновить плитку на всех $$$n$$$ площадях. Всего существует $$$k$$$ видов плитки разных цветов, пронумерованных от $$$1$$$ до $$$k$$$. Для каждой площади нужно выбрать ровно один вид плитки, который будет там уложен в процессе обновления. Чтобы сделать прогулки по центру Москвы более увлекательными, было решено назначить типы плиток площадям таким образом, чтобы для любого возможного простого пути размера ровно $$$k$$$, при прогулке вдоль этого пути встречались бы все $$$k$$$ различных типов плитки.</p><p>Определите, можно ли уложить плитку подходящим образом или нет.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$k$$$ ($$$2 \le k \le n \le 200\,000$$$) — количество площадей в Москве, количество различных цветов плитки.</p><p>Каждая из последующих $$$n - 1$$$ строк содержит по два целых числа $$$v_i$$$ и $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$) — номера площадей, соединённых данной пешеходной дорожкой.</p><p>Гарантируется, что от любой площади можно добраться до любой другой, причём единственным способом.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите «<span class="tex-font-style-tt">Yes</span>», если уложить плитку возможно, и «<span class="tex-font-style-tt">No</span>» иначе.</p><p>В случае если ваш ответ «<span class="tex-font-style-tt">Yes</span>», выведите $$$n$$$ целых чисел от $$$1$$$ до $$$k$$$ — цвет плитки для каждой площади.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 7 4 1 3 2 3 3 4 4 5 5 6 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Yes 1 1 2 3 4 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 3 1 3 2 3 3 4 4 5 5 6 5 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> No </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ниже изображена карта пешеходной зоны из первого и второго примеров, а также корректный выбор типов плитки для $$$k = 4$$$.</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/6cc7c15dbf9574a390d9ef5ea801eba64888e377.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=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 10:44: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:'812484b60ef69d40',t:'MTY5NjY2NDY2MS41OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2800"]
https://codeforces.com/blog/entry/69563
<!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="db7fdd7ce4d55f21271ce450460ac907"/> <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="Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises) - 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='db7fdd7ce4d55f21271ce450460ac907'>&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%2F69563">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='db7fdd7ce4d55f21271ce450460ac907'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(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:38:33</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:38:33</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='db7fdd7ce4d55f21271ce450460ac907'/> <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/ch_egor">ch_egor</a></li> <li class="current selectedLava"><a href="/blog/ch_egor">Blog</a></li> <li><a href="/teams/with/ch_egor">Teams</a></li> <li><a href="/submissions/ch_egor">Submissions</a></li> <li><a href="/groups/with/ch_egor">Groups</a></li> <li><a href="/contests/with/ch_egor">Contests</a></li> <li><a href="/contests/writer/ch_egor">Problemsetting</a></li> </ul> </div> <div style="margin-top:0;"> <div> <h3><a href="/blog/ch_egor" style="text-decoration:none;color:black !important;">ch_egor's blog</a></h3> </div> <div style="margin-top:2em;"> <div class="has-topic-id topic" topicId="70073"> <div class="title"> <a href="/blog/entry/69563"> <p>Editorial of Codeforces Round #583 (based on Olympiad of Metropolises)</p> </a> </div> <div class="info" style="position:relative;"> By&nbsp;<a href="/profile/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a>, <span class="format-humantime" title="Sep/04/2019 23:36">4 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"><p>Thanks for the participation!</p><p><a href="/contest/1214/problem/A">1214A - Optimal Currency Exchange</a> was authored and prepared by Helen Andreeva.</p><p><a href="/contest/1214/problem/B">1214B - Badges</a> was authored by jury and prepared by <a class="rated-user user-red" href="/profile/Chmel_Tolstiy" title="International Grandmaster Chmel_Tolstiy">Chmel_Tolstiy</a>.</p><p><a href="/contest/1214/problem/C">1214C - Bad Sequence</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-violet" href="/profile/GoToCoding" title="Candidate Master GoToCoding">GoToCoding</a>.</p><p><a href="/contest/1214/problem/D">1214D - Treasure Island</a> was authored by <a class="rated-user user-red" href="/profile/meshanya" title="Grandmaster meshanya">meshanya</a> and prepared by <a class="rated-user user-orange" href="/profile/malcolm" title="Master malcolm">malcolm</a>.</p><p><a href="/contest/1214/problem/E">1214E - Petya and Construction Set</a> was authored and prepared by <a class="rated-user user-red" href="/profile/voidmax" title="International Grandmaster voidmax">voidmax</a>.</p><p><a href="/contest/1214/problem/F">1214F - Employment</a> was authored and prepared by <a class="rated-user user-orange" href="/profile/grphil" title="Master grphil">grphil</a>.</p><p><a href="/contest/1214/problem/G">1214G - Feeling Good</a> was authored and prepared by <a class="rated-user user-red" href="/profile/isaf27" title="International Grandmaster isaf27">isaf27</a>.</p><p><a href="/contest/1214/problem/H">1214H - Tiles Placement</a> was authored and prepared by <a class="rated-user user-red" href="/profile/cdkrot" title="International Grandmaster cdkrot">cdkrot</a>.</p> <div class="problemTutorial" problemcode="1214A">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214B">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214C">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214D">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214E">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214F">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214G">Tutorial is loading...</div> <div class="problemTutorial" problemcode="1214H">Tutorial is loading...</div></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/1214" class="notice" style="text-decoration: none;">Codeforces Round 583 (Div. 1 + Div. 2, based on Olympiad of Metropolises)</a> </span> </div> <script type="text/javascript"> $(document).ready(function () { $(".delete-resource-link-42191-70073").click(function() { var that = this; Codeforces.confirm("Are you sure you want to detach a contest?", function () { $.post("/data/blogAndContest", { action: "detachBlogFromContest", blogId: "42191", blogEntryId: "69563", 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=%23editorial" class="tag notice" style="text-decoration: none;">#editorial</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-70073"><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'>+84</span> </li> <li style="line-height: 1.6em;"> <a href="#" class="topic-vote-down-70073"><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/ch_egor"><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/ch_egor"> ch_egor </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="Sep/04/2019 23:36">4 years ago</span> </li> <li> <a href="/blog/entry/69563#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/69563#comments"> 70 </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="74389"> <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 (61)</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="540741" 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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 12:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540741" href="?#comment-540741" style="font-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="540741" revisionCount="6" revision="6"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">6</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540741" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540741"> <div class="moveup"> <div class="ttypography"><p>Alternative solution for D: Treasure Island if you're using a language where sets and tuples can be expensive (e.g. JVM), is to simply convert the grid to a 2D character array. Then you can iterate through the array twice, once in forward order, once in backward order. The first time, you mark $$$(1, 1)$$$ with e.g. a '0' character, and &quot;spread&quot; the '0' characters over the '.' characters. The second time, you do the same from the goal backward, except changing from '0' to '1'. Now the '1' characters represent the intersection of the two sets of accessibility.</p><p>It's basically a BFS/DFS variant that isn't actually either, but rather &quot;reading-order first&quot;, taking advantage of the fact that successors always come later in reading order.</p><p>Sample code in Kotlin: <a href="https://codeforces.com/contest/1214/submission/60063170">#60063170</a></p><p>Problems like this and <a href="https://codeforces.com/contest/1195/problem/E">#1195E OpenStreetMap</a> really makes me wish Project Valhalla was out already. Either that or it's time for me to learn another language :P</p></div> </div> </div> <div class="reply info"> <a class="comment-540741 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540741 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540741"> <li> <div class="comment"> <table class="comment-table" commentId="540745" commentParentId="540741"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:14">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540745" href="?#comment-540745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540741" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540745" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540745"> <div class="moveup"> <div class="ttypography"><p>I think your solution of D is same as the editorial solution</p></div> </div> </div> <div class="reply info"> <a class="comment-540745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540745"> <li> <div class="comment"> <table class="comment-table" commentId="540747" commentParentId="540745"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:22">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540747" href="?#comment-540747" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540745" style="font-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="540747" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="540747" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540747"> <div class="moveup"> <div class="ttypography"><p>It's the same basic idea, and represents the same things set-theoretically, but the implementation details (using arrays rather than hash-sets, stacks/queues, and tuples) make all the difference speed-wise.</p></div> </div> </div> <div class="reply info"> <a class="comment-540747 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540747 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540747"> <li> <div class="comment"> <table class="comment-table" commentId="540751" commentParentId="540747"> <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/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540751" href="?#comment-540751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540747" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540751" class="CommentVoteFrame" data-commentRating="-8" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540751"> <div class="moveup"> <div class="ttypography"><p>The editorial never said that it had used sets, stacks/queues, tuples :(</p></div> </div> </div> <div class="reply info"> <a class="comment-540751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540751"> <li> <div class="comment"> <table class="comment-table" commentId="540752" commentParentId="540751"> <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/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540752" href="?#comment-540752" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540751" style="font-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="540752" 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="540752" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540752"> <div class="moveup"> <div class="ttypography"><p>It's implied by the suggestion to use DFS. To properly implement DFS, you need a stack (or a queue for BFS), and the most natural way to store the vertices (i.e. grid positions) is with tuples. My posted solution isn't a proper DFS nor a BFS; it takes advantage of the property for successors to always be later in &quot;reading order&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540752 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540752 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540752"> <li> <div class="comment"> <table class="comment-table" commentId="540755" commentParentId="540752"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/drogoz" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/drogoz" title="Specialist drogoz" class="rated-user user-cyan">drogoz</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540755" href="?#comment-540755" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540752" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540755" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="1164113" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540755"> <div class="moveup"> <div class="ttypography"><p>I don't know about everyone but if I want to run a dfs on this kind of grid, I will simply make a recursive call from cell(1, 1) and backward from cell(n, m) :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540755 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540755 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540755"> <li> <div class="comment"> <table class="comment-table" commentId="540757" commentParentId="540755"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/Spheniscine" style="position: relative;"> <img src='https://userpic.codeforces.org/1170595/avatar/9311eb392a3d0c8c.jpg'/> </a> <div><a href="/profile/Spheniscine" title="Master Spheniscine" class="rated-user user-orange">Spheniscine</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 13:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540757" href="?#comment-540757" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540755" style="font-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="540757" 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="540757" class="CommentVoteFrame" data-commentRating="4" data-commentUserId="1170595" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+4</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540757"> <div class="moveup"> <div class="ttypography"><p>That's technically also a stack, except you're using the call stack rather than an explicit object. :P Which also may cause problems in the JVM due to small default call-stack size. (StackOverflowException anyone?)</p></div> </div> </div> <div class="reply info"> <a class="comment-540757 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540757 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540757"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540764" 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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 14:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540764" href="?#comment-540764" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540764" class="CommentVoteFrame" data-commentRating="23" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+23</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540764"> <div class="moveup"> <div class="ttypography"><p>An easier solution for D:</p><p><img alt=" " src="/predownloaded/27/70/27709c2f2d28cf899c5edd22ff8a25c835b281d8.png" style="max-width: 100.0%;max-height: 100.0%;" /></p><p>You just need to run a maxflow.</p><p>My code: <a href="https://codeforces.com/contest/1214/submission/59996918">https://codeforces.com/contest/1214/submission/59996918</a></p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-540764 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540764 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540764"> <li> <div class="comment"> <table class="comment-table" commentId="540771" commentParentId="540764"> <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/memento" style="position: relative;"> <img src='https://userpic.codeforces.org/852933/avatar/950578c1b4afd9dc.jpg'/> </a> <div><a href="/profile/memento" title="Expert memento" class="rated-user user-blue">memento</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:16">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540771" href="?#comment-540771" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540771" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="852933" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540771"> <div class="moveup"> <div class="ttypography"><blockquote><p>Sorry for my poor English.</p> </blockquote><p>Might as well put that in the comment template.</p></div> </div> </div> <div class="reply info"> <a class="comment-540771 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540771 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540771"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540787" commentParentId="540764"> <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/lollihunter" style="position: relative;"> <img src='https://userpic.codeforces.org/669492/avatar/ae4532639872ab6.jpg'/> </a> <div><a href="/profile/lollihunter" title="International Master lollihunter" class="rated-user user-orange">lollihunter</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 16:54">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540787" href="?#comment-540787" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540787" class="CommentVoteFrame" data-commentRating="29" data-commentUserId="669492" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+29</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540787"> <div class="moveup"> <div class="ttypography"><p>Apologies, but I wouldn't call a max-flow solution &quot;an easier one&quot;.</p></div> </div> </div> <div class="reply info"> <a class="comment-540787 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540787 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540787"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540789" commentParentId="540764"> <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/saketh" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.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:5px;right:10px'/> </a> <div><a href="/profile/saketh" title="International Grandmaster saketh" class="rated-user user-red">saketh</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540789" href="?#comment-540789" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540789" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="44" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540789"> <div class="moveup"> <div class="ttypography"><p>You can implement Ford-Fulkerson implicitly in a simple way since all edges have infinite capacity and all nodes have 0/1 capacity: <a href="https://codeforces.com/contest/1214/submission/60080823">https://codeforces.com/contest/1214/submission/60080823</a>.</p><p>The find() function is called at most three times due to the observation that the min cut / max flow is at most 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-540789 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540789 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540789"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="541215" commentParentId="540764"> <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/TopCarry" style="position: relative;"> <img src='https://userpic.codeforces.org/935259/avatar/c50f5d4e1fbf4f3.jpg'/> </a> <div><a href="/profile/TopCarry" title="Candidate Master TopCarry" class="rated-user user-violet">TopCarry</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 05:58">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541215" href="?#comment-541215" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541215" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="935259" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541215"> <div class="moveup"> <div class="ttypography"><p>I think if you don't converting a Plane Graph into a Dual Graph and use Dijkstra,the complexity of the algorithm is not right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541215 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541215 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541215"> <li> <div class="comment"> <table class="comment-table" commentId="541249" commentParentId="541215"> <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/amane-ame" style="position: relative;"> <img src='https://userpic.codeforces.org/553827/avatar/d33e6df92eb1e5b9.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/amane-ame" title="Grandmaster amane-ame" class="rated-user user-red">amane-ame</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 10:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541249" href="?#comment-541249" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541215" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541249" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="553827" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541249"> <div class="moveup"> <div class="ttypography"><p>The flow is at most 2, so the complexity of Dinic is $$$\mathrm O(n+m)$$$.</p></div> </div> </div> <div class="reply info"> <a class="comment-541249 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541249 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541249"> </ul> </div> </li> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="606185" commentParentId="540764"> <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/rupav" style="position: relative;"> <img src='https://userpic.codeforces.org/808362/avatar/9f1b19f912b5ca5f.jpg'/> </a> <div><a href="/profile/rupav" title="Specialist rupav" class="rated-user user-cyan">rupav</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Apr/17/2020 09:22">3 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-606185" href="?#comment-606185" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540764" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="606185" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="808362" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-606185"> <div class="moveup"> <div class="ttypography"><p>Can you please explain why you made edges with capacity 1/0 for nodes which are empty/forests. I thought just joining edges between nodes which have a path available with capacity 1, but then that is giving WA on tc 44.</p></div> </div> </div> <div class="reply info"> <a class="comment-606185 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-606185 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-606185"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540778" 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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 15:39">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540778" href="?#comment-540778" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540778" class="CommentVoteFrame" data-commentRating="26" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+26</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540778"> <div class="moveup"> <div class="ttypography"><p>A really simple solution for D: just run a dfs and check if the destination is reachable and mark all nodes you saw. For every path you find like this you can increase the result by one. <a href="/contest/1214/submission/60075870" title="Submission 60075870 by MZuenni">60075870</a></p><p>This solution works since the corresponding graph is planar, the start and destination both lie on the outer face, and the dfs is in fact a so called &quot;right-first-dfs&quot;. </p></div> </div> </div> <div class="reply info"> <a class="comment-540778 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540778 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540778"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540788" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540788" href="?#comment-540788" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540788" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540788"> <div class="moveup"> <div class="ttypography"><p>D can actually be easily solved using Dinic's algorithm in O(N*M). At first, it's clear that max flow from (1, 1) to (n, m) will be the answer, as max flow equals min cut, which is exactly what we need to find in the problem. Now, here's why Dinicz will find max flow in this graph in O(N*M). All the edges' capacity is 1, so one faze of the algorithm will work in O(M), where M is the amount of edges in the graph. The other thing is that Dinicz will stop after the first faze. Each faze lengthens the shortest path from S to T int the net, meanwhile in this one all the paths are the shortest.</p></div> </div> </div> <div class="reply info"> <a class="comment-540788 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540788 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540788"> <li> <div class="comment"> <table class="comment-table" commentId="540790" commentParentId="540788"> <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/errorgorn" style="position: relative;"> <img src='https://userpic.codeforces.org/1160696/avatar/e9bce33c82394684.jpg'/> </a> <div><a href="/profile/errorgorn" title="International Grandmaster errorgorn" class="rated-user user-red">errorgorn</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:08">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540790" href="?#comment-540790" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540788" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540790" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1160696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540790"> <div class="moveup"> <div class="ttypography"><p>But that's hard to code unless you already have existing code for it. But its quite overkill imo</p></div> </div> </div> <div class="reply info"> <a class="comment-540790 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540790 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540790"> <li> <div class="comment"> <table class="comment-table" commentId="540791" commentParentId="540790"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 17:12">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540791" href="?#comment-540791" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540791" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540791"> <div class="moveup"> <div class="ttypography"><p>Yeah it is. I didn't actually code it on the contest, just thought about it afterwords. This problem can really help understanding flows and Dinic's algorithm better though.</p></div> </div> </div> <div class="reply info"> <a class="comment-540791 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540791 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540791"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="540953" commentParentId="540790"> <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/tfg" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/tfg" title="International Grandmaster tfg" class="rated-user user-red">tfg</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 01:20">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540953" href="?#comment-540953" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540790" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540953" class="CommentVoteFrame" data-commentRating="17" data-commentUserId="456977" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+17</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-540953"> <div class="moveup"> <div class="ttypography"><p>Not overkill if you copy+paste and code the rest in 5 minutes</p></div> </div> </div> <div class="reply info"> <a class="comment-540953 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540953 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540953"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540863" 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/never_giveup" style="position: relative;"> <img src='https://userpic.codeforces.org/230491/avatar/71c88529074d26a6.jpg'/> </a> <div><a href="/profile/never_giveup" title="Legendary Grandmaster never_giveup" class="rated-user user-legendary"><span class="legendary-user-first-letter">n</span>ever_giveup</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540863" href="?#comment-540863" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540863" class="CommentVoteFrame" data-commentRating="10" data-commentUserId="230491" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540863"> <div class="moveup"> <div class="ttypography"><p>Was ternary search by the position of the pair of the first element in F an intended solution?</p></div> </div> </div> <div class="reply info"> <a class="comment-540863 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540863 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540863"> <li> <div class="comment"> <table class="comment-table" commentId="540885" commentParentId="540863"> <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/Merkurev" style="position: relative;"> <img src='https://userpic.codeforces.org/25275/avatar/11ef25e20108954f.jpg'/> </a> <div><a href="/profile/Merkurev" title="International Grandmaster Merkurev" class="rated-user user-red">Merkurev</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 20:53">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540885" href="?#comment-540885" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540863" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540885" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="25275" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540885"> <div class="moveup"> <div class="ttypography"><p>Normal ternary search is just not correct. For example on test:</p> <pre><code>10 20 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 5 10 10 10 10 10 4 4 4 4 4 4 4 4 4 4 4 5 4 4 4 </code></pre><p>Solution <a href="/contest/1214/submission/60008635" title="Submission 60008635 by I.Smirn0ff">60008635</a> (AC on round) don't work. Because a lot of offsets give the same value, and this value is not optimal.</p><p>However there are some other implementations, for example <a href="/contest/1214/submission/60002491" title="Submission 60002491 by Apollochen">60002491</a>. There the search is for the number of people crossing 0=M bound, And for some values it calculates not the optimal score, but smth larger. And I'm curious how to challenge it :)</p></div> </div> </div> <div class="reply info"> <a class="comment-540885 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540885 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540885"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540895" 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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/05/2019 21:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540895" href="?#comment-540895" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540895" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540895"> <div class="moveup"> <div class="ttypography"><p>I see a submission using ternary search in F, why is it works? <a href="/contest/1214/submission/60035603" title="Submission 60035603 by just_soso">60035603</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540895 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540895 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540895"> <li> <div class="comment"> <table class="comment-table" commentId="541659" commentParentId="540895"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:26">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541659" href="?#comment-541659" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540895" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541659" class="CommentVoteFrame" data-commentRating="-7" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">-7</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541659"> <div class="moveup"> <div class="ttypography"><p>Consider function $$$f(x)=\sum_{i=1}^{n}|a_i-x|$$$ , it's easy to see that $$$f(x)$$$ is a lower convex function.</p><p>So the function $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|$$$ is similar to $$$f(x)$$$ if $$$a,b$$$ are non-decreasing.</p><p>And it's easy to transform the original problem to this : find the minimal value of $$$g(x)$$$ $$$(-n\leqslant x \leqslant n)$$$.</p><p>Sorry for my poor English.</p></div> </div> </div> <div class="reply info"> <a class="comment-541659 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541659 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541659"> <li> <div class="comment"> <table class="comment-table" commentId="541729" commentParentId="541659"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:24">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541729" href="?#comment-541729" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541659" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541729" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541729"> <div class="moveup"> <div class="ttypography"><p>I am sorry that I can't fully understand what's the meaning of f(x) and g(x).</p></div> </div> </div> <div class="reply info"> <a class="comment-541729 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541729 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541729"> <li> <div class="comment"> <table class="comment-table" commentId="541872" commentParentId="541729"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 03:51">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541872" href="?#comment-541872" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541729" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541872" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541872"> <div class="moveup"> <div class="ttypography"><p>Consider a greedy mathods:</p><p>transform $$$a_i$$$ to $$$a_i+m$$$, and $$$b_i$$$ to $$$b_1,b_2,\cdots ,b_n,b_{n+1}+m,\cdots, b_{2n}+m,b_{2n+1}+2m,\cdots,b_{3n}+2m$$$, after that the length of $$$b$$$ is $$$3n$$$.</p><p>then let $$$g(x)=\sum_{i=1}^{n}|a_i-b_{i+x}|(0\leqslant x\leqslant 2n-1)$$$.</p><p>it is a lower convex function because it's made up of $$$2n$$$ points in $$$f(x)$$$ from left to right.</p></div> </div> </div> <div class="reply info"> <a class="comment-541872 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541872 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541872"> <li> <div class="comment"> <table class="comment-table" commentId="541984" commentParentId="541872"> <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/just_soso" style="position: relative;"> <img src='https://userpic.codeforces.org/335696/avatar/9c998c6f17813fe1.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/just_soso" title="Master just_soso" class="rated-user user-orange">just_soso</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/10/2019 17:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541984" href="?#comment-541984" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541872" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541984" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="335696" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541984"> <div class="moveup"> <div class="ttypography"><p>This time I understand, and why this greedy method works?</p></div> </div> </div> <div class="reply info"> <a class="comment-541984 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541984 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541984"> <li> <div class="comment"> <table class="comment-table" commentId="542042" commentParentId="541984"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/11/2019 04:38">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542042" href="?#comment-542042" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541984" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542042" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542042"> <div class="moveup"> <div class="ttypography"><p>this is the same as the official editorial, maybe you can check it out.</p></div> </div> </div> <div class="reply info"> <a class="comment-542042 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542042 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542042"> <li> <div class="comment"> <table class="comment-table" commentId="542178" commentParentId="542042"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/F.J" style="position: relative;"> <img src='https://userpic.codeforces.org/743349/avatar/d02b79d7100df49d.jpg'/> </a> <div><a href="/profile/F.J" title="Master F.J" class="rated-user user-orange">F.J</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/12/2019 10:48">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-542178" href="?#comment-542178" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-542042" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="542178" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="743349" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-542178"> <div class="moveup"> <div class="ttypography"><p>Sorry, I find it's really hard to understand why this method it the same as the official editorial</p></div> </div> </div> <div class="reply info"> <a class="comment-542178 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-542178 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-542178"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540962" 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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:13">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540962" href="?#comment-540962" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540962" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540962"> <div class="moveup"> <div class="ttypography"><p>An alternative solution for D:: Use top down or bottom up approach to find the points (r,c) which can access (n,m) =&gt; those points which can traverse freely to (n,m). At this point we do not care where to create blockages. </p><p>Then observe that if we block any of the diagonal (0,0) gets cut off from (n,m). We use this fact and the information we extracted earlier to find the ans. Then use BFS from (0,0). Create a diagonal list say dp[]. As we are traversing each element, if the element (x,y) can access (n,m) we add 1 to dp[x+y].</p><p>Then we recur over this dp and find its minimum. That is the answer. <a href="https://codeforces.com/contest/1214/submission/60144916">https://codeforces.com/contest/1214/submission/60144916</a> </p></div> </div> </div> <div class="reply info"> <a class="comment-540962 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540962 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540962"> <li> <div class="comment"> <table class="comment-table" commentId="540965" commentParentId="540962"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:31">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540965" href="?#comment-540965" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540962" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540965" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540965"> <div class="moveup"> <div class="ttypography"><p>that is exactly what the sample solution does?</p></div> </div> </div> <div class="reply info"> <a class="comment-540965 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540965 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540965"> <li> <div class="comment"> <table class="comment-table" commentId="540967" commentParentId="540965"> <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/Lezendary_sandwich" style="position: relative;"> <img src='https://userpic.codeforces.org/810466/avatar/b45ba340296b4f79.jpg'/> </a> <div><a href="/profile/Lezendary_sandwich" title="Master Lezendary_sandwich" class="rated-user user-orange">Lezendary_sandwich</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:36">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540967" href="?#comment-540967" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540965" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540967" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="810466" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540967"> <div class="moveup"> <div class="ttypography"><p>They are completely two different ways to implement the same idea you could say.</p></div> </div> </div> <div class="reply info"> <a class="comment-540967 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540967 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540967"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540963" 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/black_immortal" style="position: relative;"> <img src='https://userpic.codeforces.org/671120/avatar/6c51e8074e6a1dd.jpg'/> </a> <div><a href="/profile/black_immortal" title="Specialist black_immortal" class="rated-user user-cyan">black_immortal</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:15">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540963" href="?#comment-540963" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540963" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="671120" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540963"> <div class="moveup"> <div class="ttypography"><p>For the problem <a href="/contest/1214/problem/D">1214D - Treasure Island</a>, I'm getting a TLE on test 19 — <a href="/contest/1214/submission/60144500" title="Submission 60144500 by black_immortal">60144500</a>. Can somebody please help me identify the error?</p></div> </div> </div> <div class="reply info"> <a class="comment-540963 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540963 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540963"> <li> <div class="comment"> <table class="comment-table" commentId="540968" commentParentId="540963"> <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/MZuenni" style="position: relative;"> <img src='https://userpic.codeforces.org/617893/avatar/29c0cc27efe8524b.jpg'/> </a> <div><a href="/profile/MZuenni" title="Candidate Master MZuenni" class="rated-user user-violet">MZuenni</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 02:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540968" href="?#comment-540968" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-540963" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="540968" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="617893" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540968"> <div class="moveup"> <div class="ttypography"><p>there are many things you should change (but the tle is probably due to huge constant factors...):</p><p>try to avoid a set if it will contain 10^6 elements (which can happen if I understand your code correct). 10^6 elements in a set are really much...</p><p>don't use new and delete in competitive programming. Use a vector and let it do the allocations. (this makes writing code much simpler)</p><p>don't use pointers. Use references. (again this makes things for competitive programming easier to write and we almost never need pointers)</p></div> </div> </div> <div class="reply info"> <a class="comment-540968 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540968 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540968"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="540978" 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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 05:34">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-540978" href="?#comment-540978" style="font-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="540978" 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="540978" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-540978"> <div class="moveup"> <div class="ttypography"><p>A can be solved in O(dlog(d))</p><p><a href="//codeforces.com/contest/1214/submission/60148440">My submission</a></p></div> </div> </div> <div class="reply info"> <a class="comment-540978 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-540978 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-540978"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541003" 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/soft_and_silent" style="position: relative;"> <img src='https://userpic.codeforces.org/881602/avatar/fa68970e664a58f2.jpg'/> </a> <div><a href="/profile/soft_and_silent" title="Newbie soft_and_silent" class="rated-user user-gray">soft_and_silent</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:09">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541003" href="?#comment-541003" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541003" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="881602" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541003"> <div class="moveup"> <div class="ttypography"><p>Can A problem be solved in O(1)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541003 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541003 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541003"> <li> <div class="comment"> <table class="comment-table" commentId="541010" commentParentId="541003"> <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/yijan" style="position: relative;"> <img src='https://userpic.codeforces.org/761999/avatar/1242bb893564a134.jpg'/> </a> <div><a href="/profile/yijan" title="International Master yijan" class="rated-user user-orange">yijan</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 09:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541010" href="?#comment-541010" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541003" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541010" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="761999" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541010"> <div class="moveup"> <div class="ttypography"><p>At least , O(d) is possible.</p></div> </div> </div> <div class="reply info"> <a class="comment-541010 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541010 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541010"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541025" 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/webhead" style="position: relative;"> <img src='https://userpic.codeforces.org/1202468/avatar/ccb7ab9fbeac2ca3.jpg'/> </a> <div><a href="/profile/webhead" title="Pupil webhead" class="rated-user user-green">webhead</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 10:45">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541025" href="?#comment-541025" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541025" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="1202468" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541025"> <div class="moveup"> <div class="ttypography"><p>I problem D what is the meaning of this statement &quot;f answer is one, there must exist such cell (x,y) that each path from (1,1) to (n,m) goes through that cell. Also we can notice that in each path the cell (x,y) goes on the (x+y−1)th place.&quot;</p></div> </div> </div> <div class="reply info"> <a class="comment-541025 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541025 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541025"> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541048" 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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 11:29">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541048" href="?#comment-541048" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541048" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541048"> <div class="moveup"> <div class="ttypography"><p>Isn't the pic from the H editorial incorrect? <a href="https://yadi.sk/i/l2-EjotfxWFAKA">There is a path 1-&gt;2-&gt;1</a> on the left of the diametr. Overall the editorial isn't clear. When we repeat the algorithm recursively, do we proccess it on each subtree coming out of the diametr? </p></div> </div> </div> <div class="reply info"> <a class="comment-541048 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541048 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541048"> <li> <div class="comment"> <table class="comment-table" commentId="541069" commentParentId="541048"> <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/cdkrot" style="position: relative;"> <img src='https://userpic.codeforces.org/205473/avatar/e25248506773731d.jpg'/> </a> <div><a href="/profile/cdkrot" title="International Grandmaster cdkrot" class="rated-user user-red">cdkrot</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:28">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541069" href="?#comment-541069" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541048" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541069" class="CommentVoteFrame" data-commentRating="12" data-commentUserId="205473" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+12</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541069"> <div class="moveup"> <div class="ttypography"><p>This picture only illustrates the method of coloring...</p><p>It's clear from the first statement that the answer is impossible for this case.</p></div> </div> </div> <div class="reply info"> <a class="comment-541069 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541069 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541069"> <li> <div class="comment"> <table class="comment-table" commentId="541073" commentParentId="541069"> <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/Pankin" style="position: relative;"> <img src='https://userpic.codeforces.org/574210/avatar/b5aae9c2cc10430a.jpg'/> </a> <div><a href="/profile/Pankin" title="Master Pankin" class="rated-user user-orange">Pankin</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 13:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541073" href="?#comment-541073" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541069" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541073" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="574210" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541073"> <div class="moveup"> <div class="ttypography"><p>Yeah it is I just don't get why would they use the wrong pic</p></div> </div> </div> <div class="reply info"> <a class="comment-541073 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541073 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541073"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541155" 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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/06/2019 21:04">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541155" href="?#comment-541155" style="font-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="541155" 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="541155" class="CommentVoteFrame" data-commentRating="3" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541155"> <div class="moveup"> <div class="ttypography"><p>Yet another solution to problem D — no graph algorithms required! Precompute $$$d_{i,j}$$$ — whether $$$(i,j)$$$ is reachable from $$$(1, 1)$$$. Now, greedily find two paths from $$$(n,m)$$$ to $$$(1,1)$$$, one where you prioritize moving along the x-axis, and another one where you prioritize moving along the y-axis. If these two paths intersect somewhere other than in $$$(1, 1)$$$ or $$$(n, m)$$$, you can block that cell and the answer is $$$1$$$, otherwise it's $$$2$$$.</p><p>Code: <a href="/contest/1214/submission/60184416" title="Submission 60184416 by ivan100sic">60184416</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541155 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541155 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541155"> <li> <div class="comment"> <table class="comment-table" commentId="541193" commentParentId="541155"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 00:47">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541193" href="?#comment-541193" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541155" style="font-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="541193" 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="541193" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541193"> <div class="moveup"> <div class="ttypography"><p>Nice solution!<br />But why does it work?<br />Can you please prove it (just the greedy part)?</p></div> </div> </div> <div class="reply info"> <a class="comment-541193 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541193 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541193"> <li> <div class="comment"> <table class="comment-table" commentId="541205" commentParentId="541193"> <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/ivan100sic" style="position: relative;"> <img src='https://userpic.codeforces.org/26422/avatar/611ce74705dadb74.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/ivan100sic" title="International Grandmaster ivan100sic" class="rated-user user-red">ivan100sic</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:57">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541205" href="?#comment-541205" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541193" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541205" class="CommentVoteFrame" data-commentRating="14" data-commentUserId="26422" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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;">+14</span></span> <a href="#" class="vote-for-comment" voteDirection="-1" dd="y"><img style="position:relative;top:2px;opacity:0.35;" src="//codeforces.org/s/81027/images/actions/comment-votedown-blue.png" alt="Vote: I do not like it" title="Vote: I do not like it"/></a> </span> </div> </div> <div class="comment-content comment-content-541205"> <div class="moveup"> <div class="ttypography"><p>Proof by AC :)</p><p>Just kidding, one direction is obvious, if this algorithm finds two disjoint paths, then clearly the solution is 2.</p><p>The other part is not so obvious. It's enough to show that if the two greedy paths intersect, then every valid path has to pass through these intersection vertices. This is exactly the definition of a blocking vertex.</p><p>I will show that all valid paths lie between the lowest and the highest path. Assume the contrary — some part of a valid path &quot;sticks out&quot;, say, it sticks out below the lowest path. We can use this part which sticks out to find an even lower path, meaning that our original lowest path was wrong, a contradiction.</p><p>This means that every path has to pass through every intersection vertex, because that's the only vertex between the two paths.</p></div> </div> </div> <div class="reply info"> <a class="comment-541205 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541205 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541205"> <li> <div class="comment"> <table class="comment-table" commentId="541294" commentParentId="541205"> <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/Maaddy" style="position: relative;"> <img src='https://userpic.codeforces.org/627623/avatar/6597702207547ceb.jpg'/> </a> <div><a href="/profile/Maaddy" title="Expert Maaddy" class="rated-user user-blue">Maaddy</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 14:42">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541294" href="?#comment-541294" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541205" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541294" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="627623" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541294"> <div class="moveup"> <div class="ttypography"><p>Thanks a lot!<br />Well, I find this solution the easiest to understand among all others. </p></div> </div> </div> <div class="reply info"> <a class="comment-541294 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541294 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541294"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="541204" 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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/07/2019 02:23">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541204" href="?#comment-541204" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541204" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541204"> <div class="moveup"> <div class="ttypography"><p>For D, I have written a code which similar to &quot;Permeability of soil&quot; problem.</p><p>But I am getting WA. Can someone help me with it? <a href="/contest/1214/submission/60012934" title="Submission 60012934 by SevenDeadlySins">60012934</a></p></div> </div> </div> <div class="reply info"> <a class="comment-541204 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541204 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541204"> <li> <div class="comment"> <table class="comment-table" commentId="541649" commentParentId="541204"> <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/HyscereXD" style="position: relative;"> <img src='https://userpic.codeforces.org/720739/avatar/c341ab8ab3df4e6.jpg'/> </a> <div><a href="/profile/HyscereXD" title="Master HyscereXD" class="rated-user user-orange">HyscereXD</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 13:03">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541649" href="?#comment-541649" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541204" style="font-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="541649" revisionCount="3" revision="3"> <a href="#" style="text-decoration:none;font-size:1.4rem;color:#bebebe;" class="leftRevision">&larr;</a> Rev. <span class="revision">3</span> <a href="#" style="text-decoration:none;font-size:1.4rem;visibility:hidden;color:#bebebe;" class="rightRevision">&rarr;</a> </span> &nbsp; <span commentid="541649" class="CommentVoteFrame" data-commentRating="8" data-commentUserId="720739" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541649"> <div class="moveup"> <div class="ttypography"><p>You can only move right and down, that means this sample :</p> <pre><code>5 4 .... ###. .... .### .... </code></pre><p>should be 0 instead of 1.</p></div> </div> </div> <div class="reply info"> <a class="comment-541649 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541649 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541649"> <li> <div class="comment"> <table class="comment-table" commentId="541730" commentParentId="541649"> <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/SevenDeadlySins" style="position: relative;"> <img src='https://userpic.codeforces.org/430874/avatar/b011182bef4f60f0.jpg'/> </a> <div><a href="/profile/SevenDeadlySins" title="Pupil SevenDeadlySins" class="rated-user user-green">SevenDeadlySins</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/09/2019 19:25">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-541730" href="?#comment-541730" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-541649" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="541730" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="430874" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-541730"> <div class="moveup"> <div class="ttypography"><p>Thanks</p></div> </div> </div> <div class="reply info"> <a class="comment-541730 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-541730 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-541730"> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="545693" 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:35">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545693" href="?#comment-545693" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545693" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545693"> <div class="moveup"> <div class="ttypography"><p>I have been trying to pass problem D with the following approach: Check if there is not a path between (0,0) and (n-1, m-1), then the answer is 0. Check if there is not a path between (0,0) and (n-1, m-1) without using articulation points, then the answer is 1. Otherwise the answer is 2. Submission: <a href="https://codeforces.com/contest/1214/submission/61191311">https://codeforces.com/contest/1214/submission/61191311</a></p><p>I can't figure out my mistake on code,can anyone help me?</p></div> </div> </div> <div class="reply info"> <a class="comment-545693 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545693 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545693"> <li> <div class="comment"> <table class="comment-table" commentId="545695" commentParentId="545693"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 18:49">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545695" href="?#comment-545695" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545693" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545695" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545695"> <div class="moveup"> <div class="ttypography"><div class="spoiler"><b class="spoiler-title">Simple test</b><div class="spoiler-content" style="display: none;"><pre><code>3 5 ..... ..... #.#.. </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545695 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545695 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545695"> <li> <div class="comment"> <table class="comment-table" commentId="545740" commentParentId="545695"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:44">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545740" href="?#comment-545740" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545695" style="font-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="545740" 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="545740" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545740"> <div class="moveup"> <div class="ttypography"><p>My code is actually giving the correct answer for this test case. Thank you.</p></div> </div> </div> <div class="reply info"> <a class="comment-545740 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545740 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545740"> <li> <div class="comment"> <table class="comment-table" commentId="545743" commentParentId="545740"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 22:52">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545743" href="?#comment-545743" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545743" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545743"> <div class="moveup"> <div class="ttypography"><p>I'm sorry I forgot to say that I consider the edges in both ways when checking if there is a path between (0,0) and (n-1, m-1) without using articulation points.</p></div> </div> </div> <div class="reply info"> <a class="comment-545743 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545743 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545743"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="545745" commentParentId="545740"> <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/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/25/2019 23:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545745" href="?#comment-545745" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545740" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545745" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545745"> <div class="moveup"> <div class="ttypography"><p>Are you sure? <a href="https://ideone.com/gc6HOQ">https://ideone.com/gc6HOQ</a></p></div> </div> </div> <div class="reply info"> <a class="comment-545745 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545745 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545745"> <li> <div class="comment"> <table class="comment-table" commentId="545749" commentParentId="545745"> <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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:06">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545749" href="?#comment-545749" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545745" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545749" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545749"> <div class="moveup"> <div class="ttypography"><p>I have tried with <a href="//codeforces.com/contest/1214/customtest">http://codeforces.com/contest/1214/customtest</a> and C++ 17 and then i'm getting the correct answer which is 2. </p></div> </div> </div> <div class="reply info"> <a class="comment-545749 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545749 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545749"> <li> <div class="comment"> <table class="comment-table" commentId="545751" commentParentId="545749"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/ch_egor" style="position: relative;"> <img src='https://userpic.codeforces.org/245023/avatar/e3dfbe9f9d348342.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/ch_egor" title="International Grandmaster ch_egor" class="rated-user user-red">ch_egor</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 00:18">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545751" href="?#comment-545751" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545749" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545751" class="CommentVoteFrame" data-commentRating="1" data-commentUserId="245023" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545751"> <div class="moveup"> <div class="ttypography"><p>Maybe you somehow changed the code during testing? I get 1.</p> <div class="spoiler"><b class="spoiler-title">Try this test too</b><div class="spoiler-content" style="display: none;"><pre><code>5 5 ..... .###. ..#.. .###. ..... </code></pre><p>Answer is 2</p></div></div></div> </div> </div> <div class="reply info"> <a class="comment-545751 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545751 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545751"> <li> <div class="comment"> <table class="comment-table" commentId="545753" commentParentId="545751"> <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 class="comment-no-indent"> <span>&raquo;</span> </div> <div class="comment-no-indent"> <span>&raquo;</span> </div> </div> <div class="avatar"> <a href="/profile/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 01:33">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545753" href="?#comment-545753" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545751" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545753" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545753"> <div class="moveup"> <div class="ttypography"><p>I tried it and my code outputs 2 for this test case. I have done the test using the custom invocation and c++ 17</p></div> </div> </div> <div class="reply info"> <a class="comment-545753 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545753 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545753"> <li> <div class="comment"> <table class="comment-table" commentId="545762" commentParentId="545753"> <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 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/mdallrosa" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/mdallrosa" title="Pupil mdallrosa" class="rated-user user-green">mdallrosa</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Sep/26/2019 04:46">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-545762" href="?#comment-545762" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-545753" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="545762" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="220936" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-545762"> <div class="moveup"> <div class="ttypography"><p>You are correct. My code and my solution are incorrect. Here is another test case in the same &quot;style&quot; as your test case: 5 5 ..... .#.#. .#.#. .###. .....</p><p>I think that the problem with my solution is that i'm taking into consideration the entire graph, but to use this solution i should take into consideration only the graph with the paths between (0,0) and (n-1,m-1). Thank you very much.</p></div> </div> </div> <div class="reply info"> <a class="comment-545762 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-545762 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-545762"> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="571826" 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/chypsd" style="position: relative;"> <img src='https://userpic.codeforces.org/no-avatar.jpg'/> </a> <div><a href="/profile/chypsd" title="Pupil chypsd" class="rated-user user-green">chypsd</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/07/2020 16:07">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571826" href="?#comment-571826" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="571826" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="926632" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571826"> <div class="moveup"> <div class="ttypography"><p>Can anyone explain me B question. I can't understand the test case</p></div> </div> </div> <div class="reply info"> <a class="comment-571826 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571826 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571826"> <li> <div class="comment"> <table class="comment-table" commentId="571986" commentParentId="571826"> <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/aayush_bhat1999" style="position: relative;"> <img src='https://userpic.codeforces.org/837090/avatar/64da284554397e40.jpg'/> </a> <div><a href="/profile/aayush_bhat1999" title="Expert aayush_bhat1999" class="rated-user user-blue">aayush_bhat1999</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/08/2020 21:59">4 years ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-571986" href="?#comment-571986" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-571826" style="font-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="571986" 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="571986" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="837090" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-571986"> <div class="moveup"> <div class="ttypography"><p>for 1st test case:-<br />Boys-5(b),<br />Girls-6(g),<br />participants-3.<br />Possibilities of participants:-<br />1. 0b,3g<br />2. 1b,2g<br />3. 2b,1g<br />4. 3b,0g<br />so answer is 4</p></div> </div> </div> <div class="reply info"> <a class="comment-571986 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-571986 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-571986"> </ul> </div> </li> </ul> </div> <div class="comment"> <table class="comment-table" commentId="993311" 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/CODE_LOVER4655" style="position: relative;"> <img src='https://userpic.codeforces.org/1374333/avatar/b59cc6a02a5be029.jpg'/> </a> <div><a href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655" class="rated-user user-blue">CODE_LOVER4655</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:09">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993311" href="?#comment-993311" style="font-size:1.2em;">#</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993311" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1374333" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993311"> <div class="moveup"> <div class="ttypography"><p>An alternate solution for problem D, Just block any whole path from ({1,1}-&gt;{n,m}) and if afterblocking all cells of that path you can reach target from source then answer can never be 1 it must be 2.</p> <blockquote> <blockquote> </blockquote> </blockquote></div> </div> </div> <div class="reply info"> <a class="comment-993311 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993311 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993311"> <li> <div class="comment"> <table class="comment-table" commentId="993312" commentParentId="993311"> <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/pranshukas" style="position: relative;"> <img src='https://userpic.codeforces.org/1373137/avatar/21a4b2db63bfca43.jpg'/> </a> <div><a href="/profile/pranshukas" title="Specialist pranshukas" class="rated-user user-cyan">pranshukas</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jan/16/2023 23:13">9 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-993312" href="?#comment-993312" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="993312" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1373137" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-993312"> <div class="moveup"> <div class="ttypography"><p>Thanks,<a class="rated-user user-blue" href="/profile/CODE_LOVER4655" title="Expert CODE_LOVER4655">CODE_LOVER4655</a> it helped a lot..</p></div> </div> </div> <div class="reply info"> <a class="comment-993312 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-993312 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-993312"> </ul> </div> </li> <li> <div class="comment"> <table class="comment-table" commentId="1041183" commentParentId="993311"> <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/knot_scared" style="position: relative;"> <img src='https://userpic.codeforces.org/1186903/avatar/3a02d1aff779b89e.jpg'/> </a> <div><a href="/profile/knot_scared" title="Newbie knot_scared" class="rated-user user-gray">knot_scared</a></div> </div> </td> <td class="right"> <div class="info"> <span class="item"><span class="format-humantime" title="Jun/27/2023 17:38">3 months ago</span>,</span> <span class="item"><a title="Link to comment" name="comment-1041183" href="?#comment-1041183" style="font-size:1.2em;">#</a></span> <span class="item"><a title="Parent comment" href="#comment-993311" style="font-size:1.2em;">^</a></span> <span class="item">|</span> <span style="position: relative; top: 2px;"> </span> <div style="position:absolute;right:0;top:0;"> &nbsp; <span commentid="1041183" class="CommentVoteFrame" data-commentRating="0" data-commentUserId="1186903" style="position:relative;" > <a href="#" class="vote-for-comment" voteDirection="1" dd="x"><img style="position:relative;top:3px;opacity:0.35;" src="//codeforces.org/s/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-1041183"> <div class="moveup"> <div class="ttypography"><p>Thanks, a new idea added to my armory</p></div> </div> </div> <div class="reply info"> <a class="comment-1041183 en false" href="#" style="text-decoration: none;"><span class="arrow">&rarr;</span></a> <a class="comment-1041183 en false" href="#">Reply</a> </div> </td> </tr> </table> <ul class="comment-children comment-1041183"> </ul> </div> </li> </ul> </div> <br/> <div id="editBox-74389" 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 firstPreview74389 = true; var lastPreviewContent74389 = ''; 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=74389] a.leftRevision").click(function () { window.moveCommentRevision($(this), -1); return false; }); $("div[commentableId=74389] 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-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, vote: +1}, function(data) { Codeforces.showMessage(data); }, "json"); return false; }); $(".topic-vote-down-70073").click(function () { $.post("/data/topic/vote", {topicId: 70073, _tta: Codeforces.tta(), topicRevisionId: 166538, 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:26:29</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:'812889375e3e00b8',t:'MTY5NjcwNjc4OS4zNDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
1215A
1215
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$$$ желтых карточек. Известно, что в начале матча в первой команде было $$$a_1$$$ игроков, а во второй команде было $$$a_2$$$ игроков. </p><p>Если игрок первой команды получал $$$k_1$$$ желтых карточек, то он немедленно удалялся с поля до конца игры. Если игрок второй команды получал $$$k_2$$$ желтых карточек, то он немедленно удалялся с поля до конца игры. После удаления никакой игрок не мог получить желтую карточку. Каждая из $$$n$$$ желтых карточек была показана ровно одному игроку. Игра продолжалась даже в том случае, если все игроки одной или даже обеих команд были удалены с поля. </p><p>Так как судья матча потерял свои записи о том, кому он давал желтые карточки, перед вами стоит задача определить минимальное и максимальное количество игроков, которые могли быть удалены во время финального матча.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$a_1$$$ $$$(1 \le a_1 \le 1\,000)$$$ — количество игроков в первой команде.</p><p>Во второй строке следует целое число $$$a_2$$$ $$$(1 \le a_2 \le 1\,000)$$$ — количество игроков во второй команде.</p><p>В третьей строке следует целое число $$$k_1$$$ $$$(1 \le k_1 \le 1\,000)$$$ — количество желтых карточек, после получения которых игрок первой команды удалялся с поля.</p><p>В четвертой строке следует целое число $$$k_2$$$ $$$(1 \le k_2 \le 1\,000)$$$ — количество желтых карточек, после получения которых игрок второй команды удалялся с поля.</p><p>В пятой строке следует целое число $$$n$$$ $$$(1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2)$$$ — количество желтых карточек, которые были показаны во время матча.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — минимальное и максимальное количество игроков, которые могли быть удалены во время финального матча.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 5 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 6 7 25 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 9 10 89 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере матч мог пройти таким образом, что ни один игрок не был удален, таким образом минимальное количество удаленных игроков равно $$$0$$$. Максимальное количество игроков, которые могли быть удалены, равно $$$4$$$ — три игрока из второй команды и один из первой.</p><p>Во втором примере было показано максимально возможное количество желтых карточек $$$(3 \cdot 6 + 1 \cdot 7 = 25)$$$, поэтому при любом ходе игры были удалены все игроки обеих команд.</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="696b531131fb3695a00d5212dfc14be4"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='696b531131fb3695a00d5212dfc14be4'>&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%2F1215%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='696b531131fb3695a00d5212dfc14be4'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='696b531131fb3695a00d5212dfc14be4'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='696b531131fb3695a00d5212dfc14be4'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412391"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='696b531131fb3695a00d5212dfc14be4'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412391"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_54056b0d61d5c236c0ffcf1727e26c57e95fe3d5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ желтых карточек. Известно, что в начале матча в первой команде было $$$a_1$$$ игроков, а во второй команде было $$$a_2$$$ игроков. </p><p>Если игрок первой команды получал $$$k_1$$$ желтых карточек, то он немедленно удалялся с поля до конца игры. Если игрок второй команды получал $$$k_2$$$ желтых карточек, то он немедленно удалялся с поля до конца игры. После удаления никакой игрок не мог получить желтую карточку. Каждая из $$$n$$$ желтых карточек была показана ровно одному игроку. Игра продолжалась даже в том случае, если все игроки одной или даже обеих команд были удалены с поля. </p><p>Так как судья матча потерял свои записи о том, кому он давал желтые карточки, перед вами стоит задача определить минимальное и максимальное количество игроков, которые могли быть удалены во время финального матча.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$a_1$$$ $$$(1 \le a_1 \le 1\,000)$$$ — количество игроков в первой команде.</p><p>Во второй строке следует целое число $$$a_2$$$ $$$(1 \le a_2 \le 1\,000)$$$ — количество игроков во второй команде.</p><p>В третьей строке следует целое число $$$k_1$$$ $$$(1 \le k_1 \le 1\,000)$$$ — количество желтых карточек, после получения которых игрок первой команды удалялся с поля.</p><p>В четвертой строке следует целое число $$$k_2$$$ $$$(1 \le k_2 \le 1\,000)$$$ — количество желтых карточек, после получения которых игрок второй команды удалялся с поля.</p><p>В пятой строке следует целое число $$$n$$$ $$$(1 \le n \le a_1 \cdot k_1 + a_2 \cdot k_2)$$$ — количество желтых карточек, которые были показаны во время матча.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — минимальное и максимальное количество игроков, которые могли быть удалены во время финального матча.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 3 5 1 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 1 6 7 25 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 4 9 10 89 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 9 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере матч мог пройти таким образом, что ни один игрок не был удален, таким образом минимальное количество удаленных игроков равно $$$0$$$. Максимальное количество игроков, которые могли быть удалены, равно $$$4$$$ — три игрока из второй команды и один из первой.</p><p>Во втором примере было показано максимально возможное количество желтых карточек $$$(3 \cdot 6 + 1 \cdot 7 = 25)$$$, поэтому при любом ходе игры были удалены все игроки обеих команд.</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 10:44: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:'812484bea87f7b53',t:'MTY5NjY2NDY2My4wMjUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1000"]
1215B
1215
B
ru
B. Количество произведений
<div class="problem-statement"><div class="header"><div class="title">B. Количество произведений</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>В данной задаче вам задана последовательность $$$a_1, a_2, \dots, a_n$$$, состоящая из $$$n$$$ ненулевых целых чисел (то есть $$$a_i \ne 0$$$). </p><p>Перед вами стоит задача найти два числа:</p><ol> <li> количество таких пар индексов $$$(l, r)$$$ $$$(l \le r)$$$, что произведение $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ строго отрицательно; </li><li> количество таких пар индексов $$$(l, r)$$$ $$$(l \le r)$$$, что произведение $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ строго положительно. </li></ol></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, \dots, a_n$$$ $$$(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$$$ — элементы последовательности.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — количество отрезков со строго отрицательным произведением и количество отрезков со строго положительным произведением.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 -3 3 -1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 -4 3 1 2 -4 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 28 27 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 -1 -2 -3 -4 -5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 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="7f4949784d6125c390d35a8412d41853"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='7f4949784d6125c390d35a8412d41853'>&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%2F1215%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='7f4949784d6125c390d35a8412d41853'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='7f4949784d6125c390d35a8412d41853'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='7f4949784d6125c390d35a8412d41853'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412392"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7f4949784d6125c390d35a8412d41853'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412392"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_60be5fbf511340b0cecbee7c6fdad8095f6e786b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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_1, a_2, \dots, a_n$$$, состоящая из $$$n$$$ ненулевых целых чисел (то есть $$$a_i \ne 0$$$). </p><p>Перед вами стоит задача найти два числа:</p><ol> <li> количество таких пар индексов $$$(l, r)$$$ $$$(l \le r)$$$, что произведение $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ строго отрицательно; </li><li> количество таких пар индексов $$$(l, r)$$$ $$$(l \le r)$$$, что произведение $$$a_l \cdot a_{l + 1} \dots a_{r - 1} \cdot a_r$$$ строго положительно. </li></ol></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, \dots, a_n$$$ $$$(-10^{9} \le a_i \le 10^{9}; a_i \neq 0)$$$ — элементы последовательности.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа — количество отрезков со строго отрицательным произведением и количество отрезков со строго положительным произведением.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 5 -3 3 -1 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 4 2 -4 3 1 2 -4 3 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 28 27 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 -1 -2 -3 -4 -5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9 6 </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 10:44: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:'812484c78d960056',t:'MTY5NjY2NDY2NC4zNzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "*1400"]
1215C
1215
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>У Монокарпа есть две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p><p>Монокарп хочет сделать строки $$$s$$$ и $$$t$$$ одинаковыми. Для этого он может выполнять следующие операции: выбрать в строке $$$s$$$ позицию $$$pos_1$$$, выбрать в строке $$$t$$$ позицию $$$pos_2$$$ и поменять местами буквы $$$s_{pos_1}$$$ и $$$t_{pos_2}$$$.</p><p>Перед вами стоит задача определить минимальное количество операций, которые должен сделать Монокарп, чтобы сделать строки $$$s$$$ и $$$t$$$ одинаковыми, а также вывести сами операции. Если невозможно сделать строки одинаковыми, сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — длина строк $$$s$$$ и $$$t$$$.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p><p>В третьей строке следует строка $$$t$$$ длины $$$n$$$, состоящая из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно сделать строки одинаковыми, выведите $$$-1$$$.</p><p>В противном случае, в первую строку выведите целое число $$$k$$$ — минимальное количество операций, которые нужно сделать, чтобы сделать строки одинаковыми. В каждой из следующих $$$k$$$ строк выведите по два целых числа — позицию в строке $$$s$$$ и позицию в строке $$$t$$$, которые нужно использовать для обмена букв во время очередной операции. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 abab aabb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 3 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 a b </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 babbaabb abababaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 6 1 3 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно двух операций обмена. Например, можно сначала поменять местами третью букву в строке $$$s$$$ с третьей буквой в строке $$$t$$$. После этого $$$s = $$$ «<span class="tex-font-style-tt">abbb</span>», $$$t = $$$ «<span class="tex-font-style-tt">aaab</span>». Затем нужно поменять третью букву в строке $$$s$$$ со второй буквой в строке $$$t$$$. После этого обе строки $$$s$$$ и $$$t$$$ будут равны «<span class="tex-font-style-tt">abab</span>».</p><p>Во втором примере невозможно сделать строки одинаковыми.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="1ef0cfcf910c9c135850b058e1f352b6"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='1ef0cfcf910c9c135850b058e1f352b6'>&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%2F1215%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='1ef0cfcf910c9c135850b058e1f352b6'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='1ef0cfcf910c9c135850b058e1f352b6'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='1ef0cfcf910c9c135850b058e1f352b6'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412393"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1ef0cfcf910c9c135850b058e1f352b6'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412393"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_c4b230c806b279262187acc7ea572a707c03241c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>У Монокарпа есть две строки $$$s$$$ и $$$t$$$ одинаковой длины, состоящие из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p><p>Монокарп хочет сделать строки $$$s$$$ и $$$t$$$ одинаковыми. Для этого он может выполнять следующие операции: выбрать в строке $$$s$$$ позицию $$$pos_1$$$, выбрать в строке $$$t$$$ позицию $$$pos_2$$$ и поменять местами буквы $$$s_{pos_1}$$$ и $$$t_{pos_2}$$$.</p><p>Перед вами стоит задача определить минимальное количество операций, которые должен сделать Монокарп, чтобы сделать строки $$$s$$$ и $$$t$$$ одинаковыми, а также вывести сами операции. Если невозможно сделать строки одинаковыми, сообщите об этом.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(1 \le n \le 2 \cdot 10^{5})$$$ — длина строк $$$s$$$ и $$$t$$$.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p><p>В третьей строке следует строка $$$t$$$ длины $$$n$$$, состоящая из латинских букв «<span class="tex-font-style-tt">a</span>» и «<span class="tex-font-style-tt">b</span>». </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если невозможно сделать строки одинаковыми, выведите $$$-1$$$.</p><p>В противном случае, в первую строку выведите целое число $$$k$$$ — минимальное количество операций, которые нужно сделать, чтобы сделать строки одинаковыми. В каждой из следующих $$$k$$$ строк выведите по два целых числа — позицию в строке $$$s$$$ и позицию в строке $$$t$$$, которые нужно использовать для обмена букв во время очередной операции. </p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 abab aabb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 3 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 1 a b </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 babbaabb abababaa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 6 1 3 7 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно двух операций обмена. Например, можно сначала поменять местами третью букву в строке $$$s$$$ с третьей буквой в строке $$$t$$$. После этого $$$s = $$$ «<span class="tex-font-style-tt">abbb</span>», $$$t = $$$ «<span class="tex-font-style-tt">aaab</span>». Затем нужно поменять третью букву в строке $$$s$$$ со второй буквой в строке $$$t$$$. После этого обе строки $$$s$$$ и $$$t$$$ будут равны «<span class="tex-font-style-tt">abab</span>».</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 10:44: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:'812484d01b6b9d6a',t:'MTY5NjY2NDY2NS43MjQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1500"]
1215D
1215
D
ru
D. Игра с билетом
<div class="problem-statement"><div class="header"><div class="title">D. Игра с билетом</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Монокарп и Бикарп живут в Берляндии, где все автобусные билеты состоят из $$$n$$$ цифр, при этом $$$n$$$ — четное число. Гуляя вечером, они нашли билет, некоторые цифры на котором были стерты. <span class="tex-font-style-bf">Количество позиций, в которых цифры стерты, четно</span>.</p><p>Монокарп и Бикарп решили сыграть в игру, используя найденный билет. Монокарп очень не любит счастливые билеты, в то время как Бикарп коллекционирует счастливые билеты. Билет считается счастливым, если сумма первых $$$\frac{n}{2}$$$ цифр билета равна сумме последних $$$\frac{n}{2}$$$ цифр билета.</p><p>Монокарп и Бикарп будут ходить по очереди, первый ход сделает Монокарп. На каждом своем ходу игроки будут записывать на место какой-то стертой цифры произвольную цифру от $$$0$$$ до $$$9$$$. Игра заканчивается, когда в билете не останется позиций со стертыми цифрами.</p><p>Если в конце игры билет счастливый, то в игре выиграет Бикарп. В противном случае, в игре выиграет Монокарп. Перед вами стоит задача определить победителя игры, если оба игрока будут играть оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое <span class="tex-font-style-bf">четное</span> число $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — количество цифр в билете.</p><p>Во второй строке следует строка, состоящая из $$$n$$$ цифр и знаков «<span class="tex-font-style-tt">?</span>» — билет, найденный Монокарпом и Бикарпом. Если в позиции $$$i$$$ стоит знак «<span class="tex-font-style-tt">?</span>», то цифра, стоящая в позиции $$$i$$$ в билете, была стерта. Обратите внимание, что номер билета может содержать лидирующие нули. Количество символов «<span class="tex-font-style-tt">?</span>» четно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если в игре победит Монокарп, выведите «<span class="tex-font-style-tt">Monocarp</span>» (без кавычек). В противном случае, выведите «<span class="tex-font-style-tt">Bicarp</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0523 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 ?? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 ?054??0? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 ???00? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Monocarp </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нет ни одной стертой цифры в билете, поэтому игроки не смогут сделать ни одного хода. Так как билет счастливый, то выиграет Бикарп.</p><p>Во втором примере выиграет Бикарп, для этого ему нужно поставить на место стертой цифры ту же цифру, которую поставит Монокарп на своем ходу.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="7e4cbc2d3cea088db17f5405a9f5782f"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='7e4cbc2d3cea088db17f5405a9f5782f'>&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%2F1215%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='7e4cbc2d3cea088db17f5405a9f5782f'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='7e4cbc2d3cea088db17f5405a9f5782f'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='7e4cbc2d3cea088db17f5405a9f5782f'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412394"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7e4cbc2d3cea088db17f5405a9f5782f'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412394"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b385e0125c2320d4864d70662e8c3f5283e7c88c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Монокарп и Бикарп живут в Берляндии, где все автобусные билеты состоят из $$$n$$$ цифр, при этом $$$n$$$ — четное число. Гуляя вечером, они нашли билет, некоторые цифры на котором были стерты. <span class="tex-font-style-bf">Количество позиций, в которых цифры стерты, четно</span>.</p><p>Монокарп и Бикарп решили сыграть в игру, используя найденный билет. Монокарп очень не любит счастливые билеты, в то время как Бикарп коллекционирует счастливые билеты. Билет считается счастливым, если сумма первых $$$\frac{n}{2}$$$ цифр билета равна сумме последних $$$\frac{n}{2}$$$ цифр билета.</p><p>Монокарп и Бикарп будут ходить по очереди, первый ход сделает Монокарп. На каждом своем ходу игроки будут записывать на место какой-то стертой цифры произвольную цифру от $$$0$$$ до $$$9$$$. Игра заканчивается, когда в билете не останется позиций со стертыми цифрами.</p><p>Если в конце игры билет счастливый, то в игре выиграет Бикарп. В противном случае, в игре выиграет Монокарп. Перед вами стоит задача определить победителя игры, если оба игрока будут играть оптимально.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое <span class="tex-font-style-bf">четное</span> число $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — количество цифр в билете.</p><p>Во второй строке следует строка, состоящая из $$$n$$$ цифр и знаков «<span class="tex-font-style-tt">?</span>» — билет, найденный Монокарпом и Бикарпом. Если в позиции $$$i$$$ стоит знак «<span class="tex-font-style-tt">?</span>», то цифра, стоящая в позиции $$$i$$$ в билете, была стерта. Обратите внимание, что номер билета может содержать лидирующие нули. Количество символов «<span class="tex-font-style-tt">?</span>» четно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если в игре победит Монокарп, выведите «<span class="tex-font-style-tt">Monocarp</span>» (без кавычек). В противном случае, выведите «<span class="tex-font-style-tt">Bicarp</span>» (без кавычек).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0523 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 ?? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 8 ?054??0? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Bicarp </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 ???00? </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Monocarp </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере нет ни одной стертой цифры в билете, поэтому игроки не смогут сделать ни одного хода. Так как билет счастливый, то выиграет Бикарп.</p><p>Во втором примере выиграет Бикарп, для этого ему нужно поставить на место стертой цифры ту же цифру, которую поставит Монокарп на своем ходу.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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 10:44: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:'812484d87ce916e8',t:'MTY5NjY2NDY2Ny4xMDUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1700"]
1215E
1215
E
ru
E. Шарики
<div class="problem-statement"><div class="header"><div class="title">E. Шарики</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Монокарп выложил на стол слева направо $$$n$$$ шариков, причем цвет $$$i$$$-го слева шарика равен $$$a_i$$$. Он любит порядок, поэтому захотел, чтобы все шарики одного цвета образовывали непрерывные отрезки, причем для каждого цвета этот отрезок был ровно один. </p><p>Иными словами, Монокарп хочет расположить шарики так, что для каждого цвета $$$j$$$, если самый левый шарик цвета $$$j$$$ находится в позиции $$$l$$$, а самый правый — в позиции $$$r$$$, то все шарики между позициями $$$l$$$ и $$$r$$$ должны иметь цвет $$$j$$$. Такое расположение шариков Монокарп называет упорядоченным. </p><p>Для упорядочивания шариков Монокарп может выполнять следующую операцию: выбрать пару соседних шариков и поменять их местами.</p><p>Перед вами стоит задача определить минимальное количество операций, которые должен сделать Монокарп, чтобы упорядочить шарики на столе. Обратите внимание, что не важно, в каком именно порядке будут расположены отрезки, состоящие из одноцветных шариков, главное, чтобы все шарики одинакового цвета образовывали непрерывные отрезки, и для каждого цвета такой отрезок был ровно один.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 4 \cdot 10^5)$$$ — количество шариков на столе.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 20)$$$, где $$$a_i$$$ равно цвету $$$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> 7 3 4 2 3 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 20 1 14 10 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 5 5 4 4 3 5 7 6 5 4 4 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Монокарпу достаточно сделать три обмена. Сначала он может поменять местами третий и четвертый шарики, после этого последовательность шариков станет равна $$$[3, 4, 3, 2, 4, 2, 2]$$$. Затем Монокарп может поменять местами второй и третий шарики, после этого последовательность шариков станет равна $$$[3, 3, 4, 2, 4, 2, 2]$$$. После этого Монокарпу остается поменять местами четвертый и пятый шарики, после этого последовательность шариков станет равна $$$[3, 3, 4, 4, 2, 2, 2]$$$. </p><p>Во втором примере ничего менять не нужно, так как все шарики уже лежат в удовлетворяющем Монокарпа порядке.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="baf4961ac7ff45e7cc9bdccd9cd5107e"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='baf4961ac7ff45e7cc9bdccd9cd5107e'>&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%2F1215%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='baf4961ac7ff45e7cc9bdccd9cd5107e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='baf4961ac7ff45e7cc9bdccd9cd5107e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='baf4961ac7ff45e7cc9bdccd9cd5107e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412395"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='baf4961ac7ff45e7cc9bdccd9cd5107e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412395"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_db8d4cace0243f17e2ec312481dd3e70c5ddbe4d"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Монокарп выложил на стол слева направо $$$n$$$ шариков, причем цвет $$$i$$$-го слева шарика равен $$$a_i$$$. Он любит порядок, поэтому захотел, чтобы все шарики одного цвета образовывали непрерывные отрезки, причем для каждого цвета этот отрезок был ровно один. </p><p>Иными словами, Монокарп хочет расположить шарики так, что для каждого цвета $$$j$$$, если самый левый шарик цвета $$$j$$$ находится в позиции $$$l$$$, а самый правый — в позиции $$$r$$$, то все шарики между позициями $$$l$$$ и $$$r$$$ должны иметь цвет $$$j$$$. Такое расположение шариков Монокарп называет упорядоченным. </p><p>Для упорядочивания шариков Монокарп может выполнять следующую операцию: выбрать пару соседних шариков и поменять их местами.</p><p>Перед вами стоит задача определить минимальное количество операций, которые должен сделать Монокарп, чтобы упорядочить шарики на столе. Обратите внимание, что не важно, в каком именно порядке будут расположены отрезки, состоящие из одноцветных шариков, главное, чтобы все шарики одинакового цвета образовывали непрерывные отрезки, и для каждого цвета такой отрезок был ровно один.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 4 \cdot 10^5)$$$ — количество шариков на столе.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 20)$$$, где $$$a_i$$$ равно цвету $$$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> 7 3 4 2 3 4 2 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 20 1 14 10 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 13 5 5 4 4 3 5 7 6 5 4 4 6 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Монокарпу достаточно сделать три обмена. Сначала он может поменять местами третий и четвертый шарики, после этого последовательность шариков станет равна $$$[3, 4, 3, 2, 4, 2, 2]$$$. Затем Монокарп может поменять местами второй и третий шарики, после этого последовательность шариков станет равна $$$[3, 3, 4, 2, 4, 2, 2]$$$. После этого Монокарпу остается поменять местами четвертый и пятый шарики, после этого последовательность шариков станет равна $$$[3, 3, 4, 4, 2, 2, 2]$$$. </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 10:44: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:'812484e11b1a9dae',t:'MTY5NjY2NDY2OC40NTkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "*2200"]
1215F
1215
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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Помимо жалоб на уличное освещение, в мэрию Бергорода регулярно поступают жалобы на неполадки с радиовещанием в черте города. Всего в мэрию поступило $$$n$$$ жалоб, подозрительно похожих друг на друга: в $$$i$$$-й жалобе очередной радиолюбитель упоминал две радиостанции $$$x_i$$$ и $$$y_i$$$, сигнал от которых принимается с помехами, и требовал, чтобы <span class="tex-font-style-bf">хотя бы одна</span> из этих радиостанций распространяла свой сигнал по всему городу.</p><p>Конечно же, мэр Бергорода вплотную занялся рассмотрением этих жалоб. Недавно в Бергороде была установлена новая радиовышка, способная распространять сигнал силы от $$$1$$$ до $$$M$$$ (обозначим силу сигнала радиовышки за $$$f$$$). Мэр принял решение выбрать несколько радиостанций и заключить с ними договор, чтобы жители города могли принимать их сигнал. Для заключения договора с $$$i$$$-й радиостанцией необходимо, чтобы соблюдались следующие условия:</p><ul> <li> мощность сигнала $$$f$$$ должна быть не менее $$$l_i$$$, иначе в некоторых районах города будет невозможно принимать сигнал $$$i$$$-й радиостанции; </li><li> мощность сигнала $$$f$$$ должна быть не более $$$r_i$$$, иначе сигнал смогут принять жители других населенных пунктов, не заключившие договор с $$$i$$$-й радиостанцией. </li></ul><p>Всего этого уже было достаточно, чтобы мэру было трудно выбрать мощность сигнала и радиостанции так, что все жалобы будут удовлетворены. Но позже выяснилось, что некоторые радиостанции могут использовать одни и те же частоты для распространения сигнала: всего существует $$$m$$$ пар радиостанций ($$$u_i$$$, $$$v_i$$$), использующих одни и те же частоты, и для каждой такой пары нельзя одновременно заключить договор с обеими радиостанциями. <span class="tex-font-style-bf">Если радиостанции $$$x$$$ и $$$y$$$ используют одни и те же частоты, и радиостанции $$$y$$$ и $$$z$$$ используют одни и те же частоты, это не значит, что радиостанции $$$x$$$ и $$$z$$$ используют одни и те же частоты</span>.</p><p>Мэру очень трудно проанализировать всю эту информацию и понять, с какими радиостанциями нужно заключать договоры. Помогите ему выбрать такую мощность сигнала $$$f$$$ и такое множество радиостанций, с которыми город заключит договоры, чтобы:</p><ul> <li> все жалобы жителей были удовлетворены (формально, для каждого $$$i \in [1, n]$$$ либо с радиостанцией $$$x_i$$$, либо с радиостанцией $$$y_i$$$ заключен договор); </li><li> никакие выбранные радиостанции не конфликтовали за частоты (формально, для каждого $$$i \in [1, m]$$$ либо с радиостанцией $$$u_i$$$, либо с радиостанцией $$$v_i$$$ <span class="tex-font-style-bf">не</span> заключен договор); </li><li> для каждой выбранной радиостанции соблюдаются условия на мощность сигнала (формально, для каждой выбранной радиостанции $$$i$$$ соблюдается $$$l_i \le f \le r_i$$$). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы $$$4$$$ целых числа $$$n$$$, $$$p$$$, $$$M$$$ и $$$m$$$ ($$$2 \le n, p, M, m \le 4 \cdot 10^5$$$) — количество поступивших в мэрию жалоб, количество различных радиостанций, максимальная мощность сигнала и количество пар конфликтующих радиостанций, соответственно.</p><p>Далее следуют $$$n$$$ строк, описывающих поступившие в мэрию жалобы. В каждой строке заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i &lt; y_i \le p$$$) — номера радиостанций в $$$i$$$-й жалобе). <span class="tex-font-style-bf">Все жалобы различны</span>.</p><p>Далее следуют $$$p$$$ строк, описывающих радиостанции. В каждой строке заданы два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le M$$$) — ограничения на мощность сигнала при заключении договора с $$$i$$$-й радиостанцией.</p><p>Далее следуют $$$m$$$ строк, описывающих пары конфликтующих радиостанций. В каждой строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i &lt; v_i \le p$$$) — две конфликтующие радиостанции. <span class="tex-font-style-bf">Все пары конфликтующих радиостанций различны</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует такого значения мощности сигнала и такого множества радиостанций, при которых выполнялись бы все ранее описанные условия, выведите $$$-1$$$.</p><p>Иначе в первой строке выведите два целых числа $$$k$$$ и $$$f$$$ — количество радиостанций в выбранном множестве и мощность сигнала соответственно. Во второй строке выведите $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$p$$$ — номера радиостанций, с которыми следует заключить договор (в любом порядке). Если возможных ответов несколько, выведите любой из них; не обязательно минизировать/максимизировать ни количество выбранных радиостанций, ни мощность сигнала.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 2 1 3 2 4 1 2 1 2 3 4 3 4 1 2 3 4 </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="e4894225d8f6fe17bb30d9268c57c6df"/> <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="5d51fcc847427dd88d273e3d9954b9f4b71747cf"/> <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='e4894225d8f6fe17bb30d9268c57c6df'>&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%2F1215%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='e4894225d8f6fe17bb30d9268c57c6df'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1215">Codeforces Round 585 (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='e4894225d8f6fe17bb30d9268c57c6df'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1215/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='e4894225d8f6fe17bb30d9268c57c6df'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412396"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e4894225d8f6fe17bb30d9268c57c6df'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412396"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69776" title="Codeforces Round #585 (Div. 2, по мотивам Квалификационного этапа Чемпионата Юга и Поволжья России 2019-2020)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9333:9334" 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/69815" title="Разбор Codeforces Round #585" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9353:9354" 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/1215">Задачи</a></li> <li><a href="/contest/1215/submit">Отослать</a></li> <li><a href="/contest/1215/my">Мои посылки</a></li> <li><a href="/contest/1215/status">Статус</a></li> <li><a href="/contest/1215/hacks">Взломы</a></li> <li><a href="/contest/1215/room/1">Комната</a></li> <li><a href="/contest/1215/standings">Положение</a></li> <li><a href="/contest/1215/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2a8526ed5c3102aa5d1cb03d4be3e68fb82d962c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Помимо жалоб на уличное освещение, в мэрию Бергорода регулярно поступают жалобы на неполадки с радиовещанием в черте города. Всего в мэрию поступило $$$n$$$ жалоб, подозрительно похожих друг на друга: в $$$i$$$-й жалобе очередной радиолюбитель упоминал две радиостанции $$$x_i$$$ и $$$y_i$$$, сигнал от которых принимается с помехами, и требовал, чтобы <span class="tex-font-style-bf">хотя бы одна</span> из этих радиостанций распространяла свой сигнал по всему городу.</p><p>Конечно же, мэр Бергорода вплотную занялся рассмотрением этих жалоб. Недавно в Бергороде была установлена новая радиовышка, способная распространять сигнал силы от $$$1$$$ до $$$M$$$ (обозначим силу сигнала радиовышки за $$$f$$$). Мэр принял решение выбрать несколько радиостанций и заключить с ними договор, чтобы жители города могли принимать их сигнал. Для заключения договора с $$$i$$$-й радиостанцией необходимо, чтобы соблюдались следующие условия:</p><ul> <li> мощность сигнала $$$f$$$ должна быть не менее $$$l_i$$$, иначе в некоторых районах города будет невозможно принимать сигнал $$$i$$$-й радиостанции; </li><li> мощность сигнала $$$f$$$ должна быть не более $$$r_i$$$, иначе сигнал смогут принять жители других населенных пунктов, не заключившие договор с $$$i$$$-й радиостанцией. </li></ul><p>Всего этого уже было достаточно, чтобы мэру было трудно выбрать мощность сигнала и радиостанции так, что все жалобы будут удовлетворены. Но позже выяснилось, что некоторые радиостанции могут использовать одни и те же частоты для распространения сигнала: всего существует $$$m$$$ пар радиостанций ($$$u_i$$$, $$$v_i$$$), использующих одни и те же частоты, и для каждой такой пары нельзя одновременно заключить договор с обеими радиостанциями. <span class="tex-font-style-bf">Если радиостанции $$$x$$$ и $$$y$$$ используют одни и те же частоты, и радиостанции $$$y$$$ и $$$z$$$ используют одни и те же частоты, это не значит, что радиостанции $$$x$$$ и $$$z$$$ используют одни и те же частоты</span>.</p><p>Мэру очень трудно проанализировать всю эту информацию и понять, с какими радиостанциями нужно заключать договоры. Помогите ему выбрать такую мощность сигнала $$$f$$$ и такое множество радиостанций, с которыми город заключит договоры, чтобы:</p><ul> <li> все жалобы жителей были удовлетворены (формально, для каждого $$$i \in [1, n]$$$ либо с радиостанцией $$$x_i$$$, либо с радиостанцией $$$y_i$$$ заключен договор); </li><li> никакие выбранные радиостанции не конфликтовали за частоты (формально, для каждого $$$i \in [1, m]$$$ либо с радиостанцией $$$u_i$$$, либо с радиостанцией $$$v_i$$$ <span class="tex-font-style-bf">не</span> заключен договор); </li><li> для каждой выбранной радиостанции соблюдаются условия на мощность сигнала (формально, для каждой выбранной радиостанции $$$i$$$ соблюдается $$$l_i \le f \le r_i$$$). </li></ul></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы $$$4$$$ целых числа $$$n$$$, $$$p$$$, $$$M$$$ и $$$m$$$ ($$$2 \le n, p, M, m \le 4 \cdot 10^5$$$) — количество поступивших в мэрию жалоб, количество различных радиостанций, максимальная мощность сигнала и количество пар конфликтующих радиостанций, соответственно.</p><p>Далее следуют $$$n$$$ строк, описывающих поступившие в мэрию жалобы. В каждой строке заданы два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i &lt; y_i \le p$$$) — номера радиостанций в $$$i$$$-й жалобе). <span class="tex-font-style-bf">Все жалобы различны</span>.</p><p>Далее следуют $$$p$$$ строк, описывающих радиостанции. В каждой строке заданы два целых числа $$$l_i$$$ и $$$r_i$$$ ($$$1 \le l_i \le r_i \le M$$$) — ограничения на мощность сигнала при заключении договора с $$$i$$$-й радиостанцией.</p><p>Далее следуют $$$m$$$ строк, описывающих пары конфликтующих радиостанций. В каждой строке заданы два целых числа $$$u_i$$$ и $$$v_i$$$ ($$$1 \le u_i &lt; v_i \le p$$$) — две конфликтующие радиостанции. <span class="tex-font-style-bf">Все пары конфликтующих радиостанций различны</span>.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если не существует такого значения мощности сигнала и такого множества радиостанций, при которых выполнялись бы все ранее описанные условия, выведите $$$-1$$$.</p><p>Иначе в первой строке выведите два целых числа $$$k$$$ и $$$f$$$ — количество радиостанций в выбранном множестве и мощность сигнала соответственно. Во второй строке выведите $$$k$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$p$$$ — номера радиостанций, с которыми следует заключить договор (в любом порядке). Если возможных ответов несколько, выведите любой из них; не обязательно минизировать/максимизировать ни количество выбранных радиостанций, ни мощность сигнала.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 1 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 4 4 2 1 3 2 4 1 2 1 2 3 4 3 4 1 2 3 4 </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 10:44: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:'812484ea6813064b',t:'MTY5NjY2NDY2OS45MjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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)", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["2-sat", "*2700"]
1216A
1216
A
ru
A. Префиксы
<div class="problem-statement"><div class="header"><div class="title">A. Префиксы</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>У Николая есть строка $$$s$$$ <span class="tex-font-style-bf">четной</span> длины $$$n$$$, состоящая из латинских букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'. Позиции букв пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Он хочет изменить свою строку таким образом, чтобы в любом её префиксе <span class="tex-font-style-bf">четной</span> длины было поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'. Для этого Николай может производить следующую операцию любое количество раз (возможно, нулевое): выбрать позицию в своей строке и заменить букву на этой позиции на другую (то есть заменить букву '<span class="tex-font-style-tt">a</span>' на букву '<span class="tex-font-style-tt">b</span>' или заменить букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>'). Использовать какие-либо другие буквы, кроме '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>', Николай не может.</p><p>Префиксом строки $$$s$$$ длины $$$l$$$ ($$$1 \le l \le n$$$) называется строка $$$s[1..l]$$$.</p><p>Например, для строки $$$s=$$$«abba» существует два префикса чётной длины. Первый из них — это $$$s[1\dots2]=$$$«ab», второй из них — это $$$s[1\dots4]=$$$«abba». Оба префикса содержат одинаковое количество букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p><p>Ваша задача — посчитать минимальное количество операций, которое должен сделать Николай со строкой $$$s$$$, чтобы в любом ее префиксе <span class="tex-font-style-bf">четной</span> длины строки стало поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует одно целое четное число $$$n$$$ $$$(2 \le n \le 2\cdot10^{5})$$$ — длина строки $$$s$$$.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая из латинских букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первую строку выведите минимальное количество операций, которые Николай должен произвести со строкой $$$s$$$, чтобы в любом префиксе ее префиксе <span class="tex-font-style-bf">четной</span> длины стало поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p><p>Во вторую строку выведите строку Николая после проведения им всех операций. Если ответов несколько, разрешается вывести любой из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 bbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 abba </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 ababab </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 ababab </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 aa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 ba </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Николай должен произвести две операции. Например, он может заменить первую букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>' и заменить последнюю букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>'. </p><p>Во втором примере не нужно заменять никакие буквы, так как в любом префиксе четной длины исходной строки содержится поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="99ac2faa262300a983975e978b47edb5"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='99ac2faa262300a983975e978b47edb5'>&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%2F1216%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='99ac2faa262300a983975e978b47edb5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='99ac2faa262300a983975e978b47edb5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Префикс- и 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='99ac2faa262300a983975e978b47edb5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416600"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='99ac2faa262300a983975e978b47edb5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416600"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3322f3d9146e26f9d418fa27444896f81d6ee3bc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>У Николая есть строка $$$s$$$ <span class="tex-font-style-bf">четной</span> длины $$$n$$$, состоящая из латинских букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'. Позиции букв пронумерованы от $$$1$$$ до $$$n$$$.</p><p>Он хочет изменить свою строку таким образом, чтобы в любом её префиксе <span class="tex-font-style-bf">четной</span> длины было поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'. Для этого Николай может производить следующую операцию любое количество раз (возможно, нулевое): выбрать позицию в своей строке и заменить букву на этой позиции на другую (то есть заменить букву '<span class="tex-font-style-tt">a</span>' на букву '<span class="tex-font-style-tt">b</span>' или заменить букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>'). Использовать какие-либо другие буквы, кроме '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>', Николай не может.</p><p>Префиксом строки $$$s$$$ длины $$$l$$$ ($$$1 \le l \le n$$$) называется строка $$$s[1..l]$$$.</p><p>Например, для строки $$$s=$$$«abba» существует два префикса чётной длины. Первый из них — это $$$s[1\dots2]=$$$«ab», второй из них — это $$$s[1\dots4]=$$$«abba». Оба префикса содержат одинаковое количество букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p><p>Ваша задача — посчитать минимальное количество операций, которое должен сделать Николай со строкой $$$s$$$, чтобы в любом ее префиксе <span class="tex-font-style-bf">четной</span> длины строки стало поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует одно целое четное число $$$n$$$ $$$(2 \le n \le 2\cdot10^{5})$$$ — длина строки $$$s$$$.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая из латинских букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первую строку выведите минимальное количество операций, которые Николай должен произвести со строкой $$$s$$$, чтобы в любом префиксе ее префиксе <span class="tex-font-style-bf">четной</span> длины стало поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p><p>Во вторую строку выведите строку Николая после проведения им всех операций. Если ответов несколько, разрешается вывести любой из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 bbbb </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 abba </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 ababab </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 ababab </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 aa </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 ba </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Николай должен произвести две операции. Например, он может заменить первую букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>' и заменить последнюю букву '<span class="tex-font-style-tt">b</span>' на букву '<span class="tex-font-style-tt">a</span>'. </p><p>Во втором примере не нужно заменять никакие буквы, так как в любом префиксе четной длины исходной строки содержится поровну букв '<span class="tex-font-style-tt">a</span>' и '<span class="tex-font-style-tt">b</span>'.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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 10:44: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:'812484f2bb2d2de4',t:'MTY5NjY2NDY3MS4zMzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
1216B
1216
B
ru
B. Стрельба
<div class="problem-statement"><div class="header"><div class="title">B. Стрельба</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вася недавно начал тренироваться стрельбе из пистолета. Сегодня тренер предложил ему следующее задание. Он выставил на стол $$$n$$$ банок в ряд. Банки пронумерованы слева направо от $$$1$$$ до $$$n$$$. Чтобы выполнить задание, Васе предстоит сбить каждую из банок ровно по одному разу. При этом <span class="tex-font-style-bf">порядок</span>, в котором Вася будет сбивать банки, он выбирает <span class="tex-font-style-bf">самостоятельно</span>.</p><p>Вася знает, что <span class="tex-font-style-it">прочность</span> $$$i$$$-й банки равна $$$a_i$$$. Это значит, что если Вася уже сбил $$$x$$$ банок и сейчас начнет стрелять в $$$i$$$-ю банку, то, чтобы сбить эту банку, ему понадобится $$$(a_i \cdot x + 1)$$$ выстрел. Считайте, что если Вася начал стрелять в банку номер $$$i$$$, то он будет стрелять в нее, пока он ее не собьет.</p><p>Определите такой порядок стрельбы по банкам, что Вася сделает минимально возможное количество выстрелов, чтобы сбить каждую из $$$n$$$ банок ровно по одному разу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — количество банок.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, где $$$a_i$$$ равно прочности $$$i$$$-й банки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первую строку выведите минимальное количество выстрелов, которые должен сделать Вася, чтобы сбить каждую из $$$n$$$ банок ровно по одному разу.</p><p>Во вторую строку выведите последовательность из $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$n$$$ — номера банок в том порядке, в котором Вася должен по ним стрелять, чтобы минимизировать количество выстрелов. Если подходящих последовательностей несколько, разрешается вывести любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 20 10 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 43 1 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 10 10 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 64 2 1 4 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 5 4 5 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 69 6 1 3 5 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Вася может сначала стрелять в первую банку. Он собьет ее с первого выстрела, так как до этого не сбивал ни одну банку. После этого он должен стрелять в третью банку. Чтобы сбить ее, он потратит $$$20 \cdot 1 + 1 = 21$$$ выстрел. После этого останется только вторая банка. Чтобы сбить ее, Вася сделает $$$10 \cdot 2 + 1 = 21$$$ выстрел. Таким образом, суммарно Вася сделает $$$1 + 21 + 21 = 43$$$ выстрела.</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="8ab2f0e6beae82870d9ebe4eeedbf7bc"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='8ab2f0e6beae82870d9ebe4eeedbf7bc'>&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%2F1216%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='8ab2f0e6beae82870d9ebe4eeedbf7bc'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='8ab2f0e6beae82870d9ebe4eeedbf7bc'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='8ab2f0e6beae82870d9ebe4eeedbf7bc'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416601"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='8ab2f0e6beae82870d9ebe4eeedbf7bc'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416601"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2b8f7d98910e846262dfb75b3628e9c353b2d8f7"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ до $$$n$$$. Чтобы выполнить задание, Васе предстоит сбить каждую из банок ровно по одному разу. При этом <span class="tex-font-style-bf">порядок</span>, в котором Вася будет сбивать банки, он выбирает <span class="tex-font-style-bf">самостоятельно</span>.</p><p>Вася знает, что <span class="tex-font-style-it">прочность</span> $$$i$$$-й банки равна $$$a_i$$$. Это значит, что если Вася уже сбил $$$x$$$ банок и сейчас начнет стрелять в $$$i$$$-ю банку, то, чтобы сбить эту банку, ему понадобится $$$(a_i \cdot x + 1)$$$ выстрел. Считайте, что если Вася начал стрелять в банку номер $$$i$$$, то он будет стрелять в нее, пока он ее не собьет.</p><p>Определите такой порядок стрельбы по банкам, что Вася сделает минимально возможное количество выстрелов, чтобы сбить каждую из $$$n$$$ банок ровно по одному разу.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 1\,000)$$$ — количество банок.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(1 \le a_i \le 1\,000)$$$, где $$$a_i$$$ равно прочности $$$i$$$-й банки.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первую строку выведите минимальное количество выстрелов, которые должен сделать Вася, чтобы сбить каждую из $$$n$$$ банок ровно по одному разу.</p><p>Во вторую строку выведите последовательность из $$$n$$$ <span class="tex-font-style-bf">различных</span> целых чисел от $$$1$$$ до $$$n$$$ — номера банок в том порядке, в котором Вася должен по ним стрелять, чтобы минимизировать количество выстрелов. Если подходящих последовательностей несколько, разрешается вывести любую из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 20 10 20 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 43 1 3 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 10 10 10 10 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 64 2 1 4 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 5 4 5 4 4 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 69 6 1 3 5 2 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере Вася может сначала стрелять в первую банку. Он собьет ее с первого выстрела, так как до этого не сбивал ни одну банку. После этого он должен стрелять в третью банку. Чтобы сбить ее, он потратит $$$20 \cdot 1 + 1 = 21$$$ выстрел. После этого останется только вторая банка. Чтобы сбить ее, Вася сделает $$$10 \cdot 2 + 1 = 21$$$ выстрел. Таким образом, суммарно Вася сделает $$$1 + 21 + 21 = 43$$$ выстрела.</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 10:44: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:'812484fb7d3d164e',t:'MTY5NjY2NDY3Mi42NTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "*900"]
1216C
1216
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>На прямоугольном столе лежит белый лист бумаги. Он имеет прямоугольную форму, а его стороны параллельны сторонам стола. Если смотреть на стол сверху, и представить, что левая нижняя точка стола имеет координаты $$$(0, 0)$$$, а оси координат совпадают с левой и нижней сторонами стола, то левый нижний угол белого листа имеет координаты $$$(x_1, y_1)$$$, а правый верхний — $$$(x_2, y_2)$$$.</p><p>После этого на стол положили два черных листа бумаги. Стороны обоих черных листов параллельны сторонам стола. Координаты левого нижнего угла первого черного листа равны $$$(x_3, y_3)$$$, а правого верхнего — $$$(x_4, y_4)$$$. Координаты левого нижнего угла второго черного листа равны $$$(x_5, y_5)$$$, а правого верхнего — $$$(x_6, y_6)$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/10a00436065f72be8a399488eb32ccfcd4676460.png" style="max-width: 100.0%;max-height: 100.0%;"/> <span class="tex-font-size-small">Пример расположения трёх прямоугольников.</span> </center><p>Определите, осталось видно хотя бы часть белого листа, если смотреть на стол сверху, после того, как на стол положили два черных листа. Часть белого листа видно в том случае, если существует хотя бы одна точка, лежащая <span class="tex-font-style-bf">нестрого внутри</span> белого листа и лежащая <span class="tex-font-style-bf">строго вне</span> обоих черных листов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют четыре целых числа $$$x_1, y_1, x_2, y_2$$$ $$$(0 \le x_1 &lt; x_2 \le 10^{6}, 0 \le y_1 &lt; y_2 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов белого листа.</p><p>Во второй строке следуют четыре целых числа $$$x_3, y_3, x_4, y_4$$$ $$$(0 \le x_3 &lt; x_4 \le 10^{6}, 0 \le y_3 &lt; y_4 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов первого черного листа.</p><p>В третьей строке следуют четыре целых числа $$$x_5, y_5, x_6, y_6$$$ $$$(0 \le x_5 &lt; x_6 \le 10^{6}, 0 \le y_5 &lt; y_6 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов второго черного листа.</p><p><span class="tex-font-style-bf">Стороны каждого листа бумаги параллельны (перпендикулярны) осям координат.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если после того, как на стол положили два черных листа, осталось видно хотя бы часть белого листа, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек). В противном случае, выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 4 4 1 1 3 5 3 1 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 7 5 0 0 4 6 0 0 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 10 5 3 1 7 6 8 1 11 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 0 0 1000000 1000000 0 0 499999 1000000 500000 0 1000000 1000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере белый лист полностью будет покрыт черными листами.</p><p>Во втором примере часть белого листа будет видно, после того, как на стол положили два черных листа. Например, точка $$$(6.5, 4.5)$$$ лежит нестрого внутри белого листа и лежит строго вне обоих черных листов.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="e6405cd5d11478b0fb3bf3d473a77c4b"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='e6405cd5d11478b0fb3bf3d473a77c4b'>&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%2F1216%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='e6405cd5d11478b0fb3bf3d473a77c4b'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='e6405cd5d11478b0fb3bf3d473a77c4b'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='e6405cd5d11478b0fb3bf3d473a77c4b'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416602"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='e6405cd5d11478b0fb3bf3d473a77c4b'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416602"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0fa37592028fd2a6fa100650c0fdb066fed81bd2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>На прямоугольном столе лежит белый лист бумаги. Он имеет прямоугольную форму, а его стороны параллельны сторонам стола. Если смотреть на стол сверху, и представить, что левая нижняя точка стола имеет координаты $$$(0, 0)$$$, а оси координат совпадают с левой и нижней сторонами стола, то левый нижний угол белого листа имеет координаты $$$(x_1, y_1)$$$, а правый верхний — $$$(x_2, y_2)$$$.</p><p>После этого на стол положили два черных листа бумаги. Стороны обоих черных листов параллельны сторонам стола. Координаты левого нижнего угла первого черного листа равны $$$(x_3, y_3)$$$, а правого верхнего — $$$(x_4, y_4)$$$. Координаты левого нижнего угла второго черного листа равны $$$(x_5, y_5)$$$, а правого верхнего — $$$(x_6, y_6)$$$. </p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/10a00436065f72be8a399488eb32ccfcd4676460.png" style="max-width: 100.0%;max-height: 100.0%;" /> <span class="tex-font-size-small">Пример расположения трёх прямоугольников.</span> </center><p>Определите, осталось видно хотя бы часть белого листа, если смотреть на стол сверху, после того, как на стол положили два черных листа. Часть белого листа видно в том случае, если существует хотя бы одна точка, лежащая <span class="tex-font-style-bf">нестрого внутри</span> белого листа и лежащая <span class="tex-font-style-bf">строго вне</span> обоих черных листов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют четыре целых числа $$$x_1, y_1, x_2, y_2$$$ $$$(0 \le x_1 &lt; x_2 \le 10^{6}, 0 \le y_1 &lt; y_2 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов белого листа.</p><p>Во второй строке следуют четыре целых числа $$$x_3, y_3, x_4, y_4$$$ $$$(0 \le x_3 &lt; x_4 \le 10^{6}, 0 \le y_3 &lt; y_4 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов первого черного листа.</p><p>В третьей строке следуют четыре целых числа $$$x_5, y_5, x_6, y_6$$$ $$$(0 \le x_5 &lt; x_6 \le 10^{6}, 0 \le y_5 &lt; y_6 \le 10^{6})$$$ — координаты левого нижнего и правого верхнего углов второго черного листа.</p><p><span class="tex-font-style-bf">Стороны каждого листа бумаги параллельны (перпендикулярны) осям координат.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Если после того, как на стол положили два черных листа, осталось видно хотя бы часть белого листа, выведите «<span class="tex-font-style-tt">YES</span>» (без кавычек). В противном случае, выведите «<span class="tex-font-style-tt">NO</span>».</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 2 2 4 4 1 1 3 5 3 1 5 5 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> NO </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 7 5 0 0 4 6 0 0 7 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 2 10 5 3 1 7 6 8 1 11 7 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div><div class="input"><div class="title">Входные данные</div><pre> 0 0 1000000 1000000 0 0 499999 1000000 500000 0 1000000 1000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере белый лист полностью будет покрыт черными листами.</p><p>Во втором примере часть белого листа будет видно, после того, как на стол положили два черных листа. Например, точка $$$(6.5, 4.5)$$$ лежит нестрого внутри белого листа и лежит строго вне обоих черных листов.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'81248503bc889d6f',t:'MTY5NjY2NDY3My45OTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1700"]
1216D
1216
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$$$ видов мечей, которые использовались во время представлений. Каждого вида мечей было <span class="tex-font-style-bf">ровно</span> по $$$x$$$ штук. В подвал проникли $$$y$$$ человек, каждый из которых взял ровно по $$$z$$$ мечей, причем каждый человек брал мечи только <span class="tex-font-style-bf">одного вида</span>. Заметьте, что изначально вы не знаете значения $$$x, y$$$ и $$$z$$$.</p><p>На следующий день директор театра обнаружил пропажу. Пересчитав мечи, директор понял, что в подвале осталось $$$a_i$$$ мечей $$$i$$$-го вида.</p><p>Например, если $$$n=3$$$, $$$a = [3, 12, 6]$$$, то одной из возможных ситуаций является $$$x=12$$$, $$$y=5$$$ и $$$z=3$$$. Тогда первые три человека взяли мечи первого типа, а другие два взяли мечи третьего типа. Заметьте, что изначально вы не знаете значения $$$x, y$$$ и $$$z$$$, но знаете значения $$$n$$$ и $$$a$$$.</p><p>Директор не помнит, сколько изначально мечей каждого вида было в подвале, а также не знает, сколько человек проникли в подвал и сколько мечей взял каждый из них. Вам предстоит определить <span class="tex-font-style-bf">минимальное</span> количество людей $$$y$$$, которые могли проникнуть в подвал театра, а также по сколько мечей $$$z$$$ взял каждый из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — количество видов мечей.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^{9})$$$, где $$$a_i$$$ равно количеству мечей $$$i$$$-го вида, которые остались в подвале после проникновения. Гарантируется, что найдется такая пара индексов $$$(j, k)$$$, что $$$a_j \neq a_k$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа $$$y$$$ и $$$z$$$ — минимальное количество людей, которые могли проникнуть в подвал, а также количество мечей, которое взял каждый из них.</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 12 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 2 1000000000 4 6 8 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2999999987 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 13 52 0 13 26 52 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере минимальное значение $$$y$$$ равно $$$5$$$, то есть минимальное количество людей, которые могли проникнуть в подвал, равно $$$5$$$. Каждый из них взял по $$$3$$$ меча, причем трое из них взяли по $$$3$$$ меча первого вида, а двое из них взяли по $$$3$$$ меча третьего вида.</p><p>Во втором примере минимальное значение $$$y$$$ равно $$$1$$$, то есть минимальное количество людей, которые могли проникнуть в подвал, равно $$$1$$$. Этот человек взял $$$7$$$ мечей первого вида.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="ff0debd3439abbcb924a73afc82dd470"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='ff0debd3439abbcb924a73afc82dd470'>&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%2F1216%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='ff0debd3439abbcb924a73afc82dd470'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='ff0debd3439abbcb924a73afc82dd470'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='ff0debd3439abbcb924a73afc82dd470'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416603"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='ff0debd3439abbcb924a73afc82dd470'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416603"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cb2f285c2208954f63479ae46335d9c5bff57e21"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ видов мечей, которые использовались во время представлений. Каждого вида мечей было <span class="tex-font-style-bf">ровно</span> по $$$x$$$ штук. В подвал проникли $$$y$$$ человек, каждый из которых взял ровно по $$$z$$$ мечей, причем каждый человек брал мечи только <span class="tex-font-style-bf">одного вида</span>. Заметьте, что изначально вы не знаете значения $$$x, y$$$ и $$$z$$$.</p><p>На следующий день директор театра обнаружил пропажу. Пересчитав мечи, директор понял, что в подвале осталось $$$a_i$$$ мечей $$$i$$$-го вида.</p><p>Например, если $$$n=3$$$, $$$a = [3, 12, 6]$$$, то одной из возможных ситуаций является $$$x=12$$$, $$$y=5$$$ и $$$z=3$$$. Тогда первые три человека взяли мечи первого типа, а другие два взяли мечи третьего типа. Заметьте, что изначально вы не знаете значения $$$x, y$$$ и $$$z$$$, но знаете значения $$$n$$$ и $$$a$$$.</p><p>Директор не помнит, сколько изначально мечей каждого вида было в подвале, а также не знает, сколько человек проникли в подвал и сколько мечей взял каждый из них. Вам предстоит определить <span class="tex-font-style-bf">минимальное</span> количество людей $$$y$$$, которые могли проникнуть в подвал театра, а также по сколько мечей $$$z$$$ взял каждый из них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — количество видов мечей.</p><p>Во второй строке следует последовательность $$$a_1, a_2, \dots, a_n$$$ $$$(0 \le a_i \le 10^{9})$$$, где $$$a_i$$$ равно количеству мечей $$$i$$$-го вида, которые остались в подвале после проникновения. Гарантируется, что найдется такая пара индексов $$$(j, k)$$$, что $$$a_j \neq a_k$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите два целых числа $$$y$$$ и $$$z$$$ — минимальное количество людей, которые могли проникнуть в подвал, а также количество мечей, которое взял каждый из них.</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 12 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 5 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 9 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 7 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 7 2 1000000000 4 6 8 4 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2999999987 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 13 52 0 13 26 52 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 12 13 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере минимальное значение $$$y$$$ равно $$$5$$$, то есть минимальное количество людей, которые могли проникнуть в подвал, равно $$$5$$$. Каждый из них взял по $$$3$$$ меча, причем трое из них взяли по $$$3$$$ меча первого вида, а двое из них взяли по $$$3$$$ меча третьего вида.</p><p>Во втором примере минимальное значение $$$y$$$ равно $$$1$$$, то есть минимальное количество людей, которые могли проникнуть в подвал, равно $$$1$$$. Этот человек взял $$$7$$$ мечей первого вида.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'8124850c2be703eb',t:'MTY5NjY2NDY3NS4zMTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1300"]
1216E1
1216
E1
ru
E1. Числовая последовательность (простая версия)
<div class="problem-statement"><div class="header"><div class="title">E1. Числовая последовательность (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — максимальное значение $$$k$$$</span>.</p><p>Вам задана <span class="tex-font-style-it">бесконечная</span> последовательность вида «<span class="tex-font-style-tt">112123123412345$$$\dots$$$</span>», в которой следуют блоки всех последовательных целых чисел, записанных друг за другом. Первый блок содержит все числа от $$$1$$$ до $$$1$$$, второй — от $$$1$$$ до $$$2$$$, третий — от $$$1$$$ до $$$3$$$, $$$\dots$$$, $$$i$$$-й блок содержит все числа от $$$1$$$ до $$$i$$$. </p><p>Таким образом, первые $$$56$$$ элементов последовательности равны «<span class="tex-font-style-tt">11212312341234512345612345671234567812345678912345678910</span>». Элементы последовательности нумеруются с единицы. Например, $$$1$$$-й элемент последовательности равен $$$1$$$, $$$3$$$-й элемент последовательности равен $$$2$$$, $$$20$$$-й элемент последовательности равен $$$5$$$, $$$38$$$-й элемент равен $$$2$$$, $$$56$$$-й элемент последовательности равен $$$0$$$.</p><p>Перед вами стоит задача ответить на $$$q$$$ независимых запросов. Для $$$i$$$-го запроса задано целое число $$$k_i$$$. Определите элемент последовательности, который находится в позиции $$$k_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$q$$$ ($$$1 \le q \le 500$$$) — количество запросов.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк следует целое число $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — описание очередного запроса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$-ю строку должна быть выведена цифра $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — ответ на запрос номер $$$i$$$, то есть $$$x_i$$$ должно быть равно элементу последовательности, который находится в позиции $$$k_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 1 3 20 38 56 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 2 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2132 506 999999999 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 9 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответы на запросы из первого примера подробно разобраны в условии.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3b5d7e4e3383d5deb85d901f7acb525c"/> <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="Задача - E1 - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="45918201116a30ff7c514d15db3a3a543d0cc872"/> <meta name="utc_offset" content="+03:00"/> <meta name="verify-reformal" content="f56f99fd7e087fb6ccb48ef2" /> <title>Задача - E1 - Codeforces</title> <meta name="description" content="Codeforces. Соревнования и олимпиады по информатике и программированию, сообщество программистов" /> <meta name="keywords" content="программирование информатика контест олимпиада алгоритмы c++ java графы vkcup" /> <meta name="robots" content="index, follow" /> <link rel="stylesheet" href="//codeforces.org/s/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='3b5d7e4e3383d5deb85d901f7acb525c'>&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%2F1216%2Fproblem%2FE1%3Flocale%3Dru">Войти</a> | <a href="/register">Зарегистрироваться</a> </div> </div> <br style="clear: both;"/> </div> <div class="roundbox menu-box borderTopRound borderBottomRound" style=""> <div class="menu-list-container"> <ul class="menu-list main-menu-list"> <li class=""><a href="/">Главная</a></li> <li class=""><a href="/top">Топ</a></li> <li class=""><a href="/catalog">Каталог</a></li> <li class="current"><a href="/contests">Соревнования</a></li> <li class=""><a href="/gyms">Тренировки</a></li> <li class=""><a href="/problemset">Архив</a></li> <li class=""><a href="/groups">Группы</a></li> <li class=""><a href="/ratings">Рейтинг</a></li> <li class=""><a href="/edu/courses"><span class="edu-menu-item">Edu</span></a></li> <li class=""><a href="/apiHelp">API</a></li> <li class=""><a href="/calendar">Календарь</a></li> <li class=""><a href="/help">Помощь</a></li> </ul> <form method="post" action="/search"><input type='hidden' name='csrf_token' value='3b5d7e4e3383d5deb85d901f7acb525c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='3b5d7e4e3383d5deb85d901f7acb525c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='3b5d7e4e3383d5deb85d901f7acb525c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416604"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3b5d7e4e3383d5deb85d901f7acb525c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416604"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { result.push(c); } } return result.join("").split("\n").map(value => value.trim()).join("\n"); }; </script> <div class="diff-popup"> </div> <div class="problemindexholder" problemindex="E1" data-uuid="ps_aabae69fe58b490a93a4c0ee61505b0db07125f6"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">E1. Числовая последовательность (простая версия)</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p><span class="tex-font-style-bf">Единственное отличие между простой и сложной версиями — максимальное значение $$$k$$$</span>.</p><p>Вам задана <span class="tex-font-style-it">бесконечная</span> последовательность вида «<span class="tex-font-style-tt">112123123412345$$$\dots$$$</span>», в которой следуют блоки всех последовательных целых чисел, записанных друг за другом. Первый блок содержит все числа от $$$1$$$ до $$$1$$$, второй — от $$$1$$$ до $$$2$$$, третий — от $$$1$$$ до $$$3$$$, $$$\dots$$$, $$$i$$$-й блок содержит все числа от $$$1$$$ до $$$i$$$. </p><p>Таким образом, первые $$$56$$$ элементов последовательности равны «<span class="tex-font-style-tt">11212312341234512345612345671234567812345678912345678910</span>». Элементы последовательности нумеруются с единицы. Например, $$$1$$$-й элемент последовательности равен $$$1$$$, $$$3$$$-й элемент последовательности равен $$$2$$$, $$$20$$$-й элемент последовательности равен $$$5$$$, $$$38$$$-й элемент равен $$$2$$$, $$$56$$$-й элемент последовательности равен $$$0$$$.</p><p>Перед вами стоит задача ответить на $$$q$$$ независимых запросов. Для $$$i$$$-го запроса задано целое число $$$k_i$$$. Определите элемент последовательности, который находится в позиции $$$k_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$q$$$ ($$$1 \le q \le 500$$$) — количество запросов.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк следует целое число $$$k_i$$$ $$$(1 \le k_i \le 10^9)$$$ — описание очередного запроса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$-ю строку должна быть выведена цифра $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — ответ на запрос номер $$$i$$$, то есть $$$x_i$$$ должно быть равно элементу последовательности, который находится в позиции $$$k_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 1 3 20 38 56 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 2 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2132 506 999999999 1000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 9 8 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответы на запросы из первого примера подробно разобраны в условии.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=E1]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'812485145c3b16ab',t:'MTY5NjY2NDY3Ni42NDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\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", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1900"]
1216E2
1216
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">Единственное отличие между простой и сложной версиями — максимальное значение $$$k$$$</span>.</p><p>Вам задана <span class="tex-font-style-it">бесконечная</span> последовательность вида «<span class="tex-font-style-tt">112123123412345$$$\dots$$$</span>», в которой следуют блоки всех последовательных целых чисел, записанных друг за другом. Первый блок содержит все числа от $$$1$$$ до $$$1$$$, второй — от $$$1$$$ до $$$2$$$, третий — от $$$1$$$ до $$$3$$$, $$$\dots$$$, $$$i$$$-й блок содержит все числа от $$$1$$$ до $$$i$$$. </p><p>Таким образом, первые $$$56$$$ элементов последовательности равны «<span class="tex-font-style-tt">11212312341234512345612345671234567812345678912345678910</span>». Элементы последовательности нумеруются с единицы. Например, $$$1$$$-й элемент последовательности равен $$$1$$$, $$$3$$$-й элемент последовательности равен $$$2$$$, $$$20$$$-й элемент последовательности равен $$$5$$$, $$$38$$$-й элемент равен $$$2$$$, $$$56$$$-й элемент последовательности равен $$$0$$$.</p><p>Перед вами стоит задача ответить на $$$q$$$ независимых запросов. Для $$$i$$$-го запроса задано целое число $$$k_i$$$. Определите элемент последовательности, который находится в позиции $$$k_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$q$$$ ($$$1 \le q \le 500$$$) — количество запросов.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк следует целое число $$$k_i$$$ $$$(1 \le k_i \le 10^{18})$$$ — описание очередного запроса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$-ю строку должна быть выведена цифра $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — ответ на запрос номер $$$i$$$, то есть $$$x_i$$$ должно быть равно элементу последовательности, который находится в позиции $$$k_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 1 3 20 38 56 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 2 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2132 506 999999999999999999 1000000000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 4 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответы на запросы из первого примера подробно разобраны в условии.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="460c415dc79baa1f42b1b6193469505a"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='460c415dc79baa1f42b1b6193469505a'>&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%2F1216%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='460c415dc79baa1f42b1b6193469505a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='460c415dc79baa1f42b1b6193469505a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='460c415dc79baa1f42b1b6193469505a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416605"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='460c415dc79baa1f42b1b6193469505a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416605"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_4259fdde3ae0782720b0352724f87b184fd17b8f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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">Единственное отличие между простой и сложной версиями — максимальное значение $$$k$$$</span>.</p><p>Вам задана <span class="tex-font-style-it">бесконечная</span> последовательность вида «<span class="tex-font-style-tt">112123123412345$$$\dots$$$</span>», в которой следуют блоки всех последовательных целых чисел, записанных друг за другом. Первый блок содержит все числа от $$$1$$$ до $$$1$$$, второй — от $$$1$$$ до $$$2$$$, третий — от $$$1$$$ до $$$3$$$, $$$\dots$$$, $$$i$$$-й блок содержит все числа от $$$1$$$ до $$$i$$$. </p><p>Таким образом, первые $$$56$$$ элементов последовательности равны «<span class="tex-font-style-tt">11212312341234512345612345671234567812345678912345678910</span>». Элементы последовательности нумеруются с единицы. Например, $$$1$$$-й элемент последовательности равен $$$1$$$, $$$3$$$-й элемент последовательности равен $$$2$$$, $$$20$$$-й элемент последовательности равен $$$5$$$, $$$38$$$-й элемент равен $$$2$$$, $$$56$$$-й элемент последовательности равен $$$0$$$.</p><p>Перед вами стоит задача ответить на $$$q$$$ независимых запросов. Для $$$i$$$-го запроса задано целое число $$$k_i$$$. Определите элемент последовательности, который находится в позиции $$$k_i$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следует целое число $$$q$$$ ($$$1 \le q \le 500$$$) — количество запросов.</p><p>В $$$i$$$-й из следующих $$$q$$$ строк следует целое число $$$k_i$$$ $$$(1 \le k_i \le 10^{18})$$$ — описание очередного запроса.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ строк. В $$$i$$$-ю строку должна быть выведена цифра $$$x_i$$$ $$$(0 \le x_i \le 9)$$$ — ответ на запрос номер $$$i$$$, то есть $$$x_i$$$ должно быть равно элементу последовательности, который находится в позиции $$$k_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 1 3 20 38 56 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 5 2 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 2132 506 999999999999999999 1000000000000000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 8 2 4 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Ответы на запросы из первого примера подробно разобраны в условии.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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 10:44: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:'8124851ca8313a77',t:'MTY5NjY2NDY3Ny45MzMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*2200"]
1216F
1216
F
ru
F. Wi-Fi
<div class="problem-statement"><div class="header"><div class="title">F. Wi-Fi</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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$$$ комнат к интернету.</p><p>Каждая из комнат может быть подключена к интернету кабелем напрямую, стоимость подключения $$$i$$$-й комнаты равна $$$i$$$ монет.</p><p>В некоторых комнатах также есть место для установки роутера. Стоимость установки роутера в $$$i$$$-й комнате также равна $$$i$$$ монет. Вы не можете поставить роутер в комнате, в которой нет места для его установки. Когда вы ставите роутер в комнате $$$i$$$, вы подключаете все комнаты с номерами от $$$max(1,~i - k)$$$ до $$$min(n,~i + k)$$$ включительно к интернету, где $$$k$$$ — это радиус действия роутера. Значение $$$k$$$ одинаково для всех роутеров. </p><p>Определите минимальную стоимость подключения всех $$$n$$$ комнат к интернету. Считайте, что количество комнат, в которые можно установить роутеры, не превосходит количества роутеров, которые у вас есть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — количество комнат и радиус действия каждого роутера.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая только из нулей и единиц. Если $$$i$$$-й символ строки равен единице, то в $$$i$$$-й комнате есть место для установки роутера. Если $$$i$$$-й символ строки равен нулю, то в $$$i$$$-й комнате нет места для установки роутера.</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> 5 2 00100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 6 000010000100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно установить роутер в комнату $$$3$$$, тогда все комнаты будут подключены к интернету. Стоимость подключения равна $$$3$$$.</p><p>Во втором примере нельзя устанавливать роутеры ни в одну из комнат, поэтому все комнаты нужно подключать напрямую кабелем. Таким образом, стоимость подключения всех комнат равна $$$1 + 2 + 3 + 4 + 5 + 6 = 21$$$.</p><p>В третьем примере комнату $$$1$$$ нужно подключить напрямую кабелем, а в комнату $$$3$$$ установить роутер. Таким образом, стоимость подключения всех комнат равна $$$1 + 3 = 4$$$.</p><p>В четвертом примере нужно установить роутеры в комнаты $$$5$$$ и $$$10$$$. Тогда все комнаты будут подключены к интернету. Стоимость подключения равна $$$5 + 10 = 15$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="4fcbcf691bcecd4c4aac9458fdcd1d63"/> <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="45918201116a30ff7c514d15db3a3a543d0cc872"/> <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='4fcbcf691bcecd4c4aac9458fdcd1d63'>&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%2F1216%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='4fcbcf691bcecd4c4aac9458fdcd1d63'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1216">Codeforces Round 587 (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='4fcbcf691bcecd4c4aac9458fdcd1d63'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1216/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='4fcbcf691bcecd4c4aac9458fdcd1d63'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="416606"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='4fcbcf691bcecd4c4aac9458fdcd1d63'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="416606"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69913" title="Codeforces Round #587 (Div. 3)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9369:9370" 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/69954" title="Разбор Codeforces Round #587 (Div. 3)" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="10138:10139" 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/1216">Задачи</a></li> <li><a href="/contest/1216/submit">Отослать</a></li> <li><a href="/contest/1216/my">Мои посылки</a></li> <li><a href="/contest/1216/status">Статус</a></li> <li><a href="/contest/1216/hacks">Взломы</a></li> <li><a href="/contest/1216/standings">Положение</a></li> <li><a href="/contest/1216/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5eda3985bf4b0c7c33565771dae577f2616d9b0f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Wi-Fi</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</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$$$ комнат к интернету.</p><p>Каждая из комнат может быть подключена к интернету кабелем напрямую, стоимость подключения $$$i$$$-й комнаты равна $$$i$$$ монет.</p><p>В некоторых комнатах также есть место для установки роутера. Стоимость установки роутера в $$$i$$$-й комнате также равна $$$i$$$ монет. Вы не можете поставить роутер в комнате, в которой нет места для его установки. Когда вы ставите роутер в комнате $$$i$$$, вы подключаете все комнаты с номерами от $$$max(1,~i - k)$$$ до $$$min(n,~i + k)$$$ включительно к интернету, где $$$k$$$ — это радиус действия роутера. Значение $$$k$$$ одинаково для всех роутеров. </p><p>Определите минимальную стоимость подключения всех $$$n$$$ комнат к интернету. Считайте, что количество комнат, в которые можно установить роутеры, не превосходит количества роутеров, которые у вас есть.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке следуют два целых числа $$$n$$$ и $$$k$$$ ($$$1 \le n, k \le 2 \cdot 10^5$$$) — количество комнат и радиус действия каждого роутера.</p><p>Во второй строке следует строка $$$s$$$ длины $$$n$$$, состоящая только из нулей и единиц. Если $$$i$$$-й символ строки равен единице, то в $$$i$$$-й комнате есть место для установки роутера. Если $$$i$$$-й символ строки равен нулю, то в $$$i$$$-й комнате нет места для установки роутера.</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> 5 2 00100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 6 1 000000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 21 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 1 0011 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 12 6 000010000100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 15 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере достаточно установить роутер в комнату $$$3$$$, тогда все комнаты будут подключены к интернету. Стоимость подключения равна $$$3$$$.</p><p>Во втором примере нельзя устанавливать роутеры ни в одну из комнат, поэтому все комнаты нужно подключать напрямую кабелем. Таким образом, стоимость подключения всех комнат равна $$$1 + 2 + 3 + 4 + 5 + 6 = 21$$$.</p><p>В третьем примере комнату $$$1$$$ нужно подключить напрямую кабелем, а в комнату $$$3$$$ установить роутер. Таким образом, стоимость подключения всех комнат равна $$$1 + 3 = 4$$$.</p><p>В четвертом примере нужно установить роутеры в комнаты $$$5$$$ и $$$10$$$. Тогда все комнаты будут подключены к интернету. Стоимость подключения равна $$$5 + 10 = 15$$$.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=F]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'81248524faad9d67',t:'MTY5NjY2NDY3OS4zMjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2100"]
1217A
1217
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>В очередной раз вы играете в свою любимую игру. Вы уже выбрали персонажа, за которого еще не играли. У него есть базовые $$$str$$$ очков силы и $$$int$$$ очков интеллекта. Также, в начале игры, персонаж имеет $$$exp$$$ свободных очков опыта, которые вы можете вложить либо в силу, либо в интеллект (вкладывая одно очко вы можете либо увеличить силу на $$$1$$$, либо интеллект на $$$1$$$).</p><p>Так как вы хотите повеселиться, вы хотите создать тупого качка, у которого будет больше очков силы, чем интеллекта (финальная сила <span class="tex-font-style-bf">строго больше</span> финального интеллекта).</p><p>Посчитайте количество различных билдов персонажа, которые вы можете создать (все ради реиграбельности), если вы обязаны <span class="tex-font-style-bf">вложить все свободные очки</span>. Два билда считаются различными, если различаются их уровень силы и/или интеллекта.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$T$$$ ($$$1 \le T \le 100$$$) — количество запросов. Следующие $$$T$$$ строк содержат описания запросов — по одному в строке.</p><p>В этой строке заданы три целых числа $$$str$$$, $$$int$$$ и $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) — первоначальные сила, интеллект и количество свободных очков для распределения, соответственно.</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 5 3 4 2 1 0 3 5 5 4 10 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть только три подходящих билда: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ и $$$(9, 3)$$$. Во всех остальных либо персонаж получается слишком умным, либо не используются все свободные очки.</p><p>Во втором запросе есть только один возможный билд: $$$(2, 1)$$$.</p><p>В третьем запросе есть два подходящих билда: $$$(7, 6)$$$, $$$(8, 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="83211bc6034f76e19b5f65e9130f92ca"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='83211bc6034f76e19b5f65e9130f92ca'>&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%2F1217%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='83211bc6034f76e19b5f65e9130f92ca'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='83211bc6034f76e19b5f65e9130f92ca'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='83211bc6034f76e19b5f65e9130f92ca'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404643"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='83211bc6034f76e19b5f65e9130f92ca'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404643"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0f208d32de4aaecb2e19a2cee9107124d46a6d66"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>В очередной раз вы играете в свою любимую игру. Вы уже выбрали персонажа, за которого еще не играли. У него есть базовые $$$str$$$ очков силы и $$$int$$$ очков интеллекта. Также, в начале игры, персонаж имеет $$$exp$$$ свободных очков опыта, которые вы можете вложить либо в силу, либо в интеллект (вкладывая одно очко вы можете либо увеличить силу на $$$1$$$, либо интеллект на $$$1$$$).</p><p>Так как вы хотите повеселиться, вы хотите создать тупого качка, у которого будет больше очков силы, чем интеллекта (финальная сила <span class="tex-font-style-bf">строго больше</span> финального интеллекта).</p><p>Посчитайте количество различных билдов персонажа, которые вы можете создать (все ради реиграбельности), если вы обязаны <span class="tex-font-style-bf">вложить все свободные очки</span>. Два билда считаются различными, если различаются их уровень силы и/или интеллекта.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке задано единственное число $$$T$$$ ($$$1 \le T \le 100$$$) — количество запросов. Следующие $$$T$$$ строк содержат описания запросов — по одному в строке.</p><p>В этой строке заданы три целых числа $$$str$$$, $$$int$$$ и $$$exp$$$ ($$$1 \le str, int \le 10^8$$$, $$$0 \le exp \le 10^8$$$) — первоначальные сила, интеллект и количество свободных очков для распределения, соответственно.</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 5 3 4 2 1 0 3 5 5 4 10 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 1 2 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе есть только три подходящих билда: $$$(str = 7, int = 5)$$$, $$$(8, 4)$$$ и $$$(9, 3)$$$. Во всех остальных либо персонаж получается слишком умным, либо не используются все свободные очки.</p><p>Во втором запросе есть только один возможный билд: $$$(2, 1)$$$.</p><p>В третьем запросе есть два подходящих билда: $$$(7, 6)$$$, $$$(8, 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 10:44: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:'8124852d586c163a',t:'MTY5NjY2NDY4MC42OTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1300"]
1217B
1217
B
ru
B. Змей Горыныч
<div class="problem-statement"><div class="header"><div class="title">B. Змей Горыныч</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы сражаетесь со Змеем Горынычем — со свирепым монстром из славянских легенд!</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a47f0ab5c3264131a3cb9149839e601526871dee.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Изначально у Змея Горыныча $$$x$$$ голов. Вы можете наносить ему $$$n$$$ типов ударов. Если вы нанесете удар $$$i$$$-го типа, вы уменьшите количество голов Горыныча на $$$min(d_i, curX)$$$, где $$$curX$$$ — текущее количество голов. Но если после этого удара у Горыныча осталась хотя бы одна голова, у него отрастает $$$h_i$$$ новых голов. Если $$$curX = 0$$$, то Горыныч побежден. </p><p><span class="tex-font-style-bf">Каждый удар можно наносить любое количество раз, сами удары можно наносить в любом порядке.</span></p><p>Например, если $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$, то после удара количество голов станет равным $$$13$$$ (вы отрубаете $$$7$$$ голов, но после этого у Горыныча отрастает $$$10$$$ новых), но если $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$, то после удара количество голов станет равным $$$0$$$ и Горыныч считается побежденным.</p><p>Посчитайте минимальное количество ударов для победы над Змеем Горынычем!</p><p>Вам нужно ответить на $$$t$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) – количество запросов.</p><p>Первая строка каждого запроса содержит два числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — количество возможных типов ударов и изначальное количество голов Змея Горыныча соответственно.</p><p>Следующие $$$n$$$ строк содержат описания возможных ударов. $$$i$$$-я строка содержит два числа $$$d_i$$$ и $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — описание $$$i$$$-го удара.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите минимальное количество ударов для победы над Змеем Горынычем. </p><p>Если Змея Горыныча нельзя победить выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы может нанести первый удар (после этого количество голов станет равно $$$10 - 6 + 3 = 7$$$), а затем нанести второй удар.</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="5b25594dc1abc5208188f2940afbcfa1"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='5b25594dc1abc5208188f2940afbcfa1'>&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%2F1217%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='5b25594dc1abc5208188f2940afbcfa1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='5b25594dc1abc5208188f2940afbcfa1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='5b25594dc1abc5208188f2940afbcfa1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404644"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5b25594dc1abc5208188f2940afbcfa1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404644"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a18f0440acac22e0fbad9ee3357b416801c7a629"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вы сражаетесь со Змеем Горынычем — со свирепым монстром из славянских легенд!</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/a47f0ab5c3264131a3cb9149839e601526871dee.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Изначально у Змея Горыныча $$$x$$$ голов. Вы можете наносить ему $$$n$$$ типов ударов. Если вы нанесете удар $$$i$$$-го типа, вы уменьшите количество голов Горыныча на $$$min(d_i, curX)$$$, где $$$curX$$$ — текущее количество голов. Но если после этого удара у Горыныча осталась хотя бы одна голова, у него отрастает $$$h_i$$$ новых голов. Если $$$curX = 0$$$, то Горыныч побежден. </p><p><span class="tex-font-style-bf">Каждый удар можно наносить любое количество раз, сами удары можно наносить в любом порядке.</span></p><p>Например, если $$$curX = 10$$$, $$$d = 7$$$, $$$h = 10$$$, то после удара количество голов станет равным $$$13$$$ (вы отрубаете $$$7$$$ голов, но после этого у Горыныча отрастает $$$10$$$ новых), но если $$$curX = 10$$$, $$$d = 11$$$, $$$h = 100$$$, то после удара количество голов станет равным $$$0$$$ и Горыныч считается побежденным.</p><p>Посчитайте минимальное количество ударов для победы над Змеем Горынычем!</p><p>Вам нужно ответить на $$$t$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 100$$$) – количество запросов.</p><p>Первая строка каждого запроса содержит два числа $$$n$$$ и $$$x$$$ ($$$1 \le n \le 100$$$, $$$1 \le x \le 10^9$$$) — количество возможных типов ударов и изначальное количество голов Змея Горыныча соответственно.</p><p>Следующие $$$n$$$ строк содержат описания возможных ударов. $$$i$$$-я строка содержит два числа $$$d_i$$$ и $$$h_i$$$ ($$$1 \le d_i, h_i \le 10^9$$$) — описание $$$i$$$-го удара.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите минимальное количество ударов для победы над Змеем Горынычем. </p><p>Если Змея Горыныча нельзя победить выведите $$$-1$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 10 6 3 8 2 1 4 4 10 4 1 3 2 2 6 1 100 2 15 10 11 14 100 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 3 -1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы может нанести первый удар (после этого количество голов станет равно $$$10 - 6 + 3 = 7$$$), а затем нанести второй удар.</p><p>Во втором запросе вы можете нанести первый удар три раза подряд — и Горыныч побежден. </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 10:44: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:'81248536092f9d55',t:'MTY5NjY2NDY4Mi4wMzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1600"]
1217C
1217
C
ru
C. Количество хороших подстрок
<div class="problem-statement"><div class="header"><div class="title">C. Количество хороших подстрок</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана бинарная строка $$$s$$$ (эта строка содержит только цифры $$$0$$$ и $$$1$$$).</p><p>Пусть $$$f(t)$$$ — десятичное представление числа $$$t$$$, записанного в двоичном виде (возможно с лидирующими нулями). Например $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ и $$$f(000100) = 4$$$.</p><p>Подстрока $$$s_{l}, s_{l+1}, \dots , s_{r}$$$ хорошая, если $$$r - l + 1 = f(s_l \dots s_r)$$$.</p><p>Например, строка $$$s = 1011$$$ имеет $$$5$$$ хороших подстрок: $$$s_1 \dots s_1 = 1$$$, $$$s_3 \dots s_3 = 1$$$, $$$s_4 \dots s_4 = 1$$$, $$$s_1 \dots s_2 = 10$$$ и $$$s_2 \dots s_4 = 011$$$. </p><p>Вам нужно посчитать количество хороших подстрок строки $$$s$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество запросов.</p><p>Каждый запрос содержит единственную строку $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), состоящую только из цифр $$$0$$$ и $$$1$$$.</p><p>Гарантируется что $$$\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество хороших подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0110 0101 00001000 0001000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 4 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="f29381171e17f291202dc7e06fff645d"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='f29381171e17f291202dc7e06fff645d'>&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%2F1217%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='f29381171e17f291202dc7e06fff645d'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='f29381171e17f291202dc7e06fff645d'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='f29381171e17f291202dc7e06fff645d'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404645"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='f29381171e17f291202dc7e06fff645d'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404645"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8ffc02aa6f79043948e53e528454ced890a32231"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>4 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам задана бинарная строка $$$s$$$ (эта строка содержит только цифры $$$0$$$ и $$$1$$$).</p><p>Пусть $$$f(t)$$$ — десятичное представление числа $$$t$$$, записанного в двоичном виде (возможно с лидирующими нулями). Например $$$f(011) = 3, f(00101) = 5, f(00001) = 1, f(10) = 2, f(000) = 0$$$ и $$$f(000100) = 4$$$.</p><p>Подстрока $$$s_{l}, s_{l+1}, \dots , s_{r}$$$ хорошая, если $$$r - l + 1 = f(s_l \dots s_r)$$$.</p><p>Например, строка $$$s = 1011$$$ имеет $$$5$$$ хороших подстрок: $$$s_1 \dots s_1 = 1$$$, $$$s_3 \dots s_3 = 1$$$, $$$s_4 \dots s_4 = 1$$$, $$$s_1 \dots s_2 = 10$$$ и $$$s_2 \dots s_4 = 011$$$. </p><p>Вам нужно посчитать количество хороших подстрок строки $$$s$$$.</p><p>Вам нужно ответить на $$$t$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$t$$$ ($$$1 \le t \le 1000$$$) — количество запросов.</p><p>Каждый запрос содержит единственную строку $$$s$$$ ($$$1 \le |s| \le 2 \cdot 10^5$$$), состоящую только из цифр $$$0$$$ и $$$1$$$.</p><p>Гарантируется что $$$\sum\limits_{i=1}^{t} |s_i| \le 2 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите одно число — количество хороших подстрок строки $$$s$$$.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 0110 0101 00001000 0001000 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 3 4 3 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=C]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:44: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:'8124853e7be9164e',t:'MTY5NjY2NDY4My4zOTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1700"]
1217D
1217
D
ru
D. Покраска ребер
<div class="problem-statement"><div class="header"><div class="title">D. Покраска ребер</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>1 секунда</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вам дан ориентированный граф из $$$n$$$ вершин и $$$m$$$ ориентированных ребер. Гарантируется, что в нем нет ни петель, ни кратных ребер.</p><p>Определим $$$k$$$-покраску орграфа следующим образом: мы красим каждое ребро в один из $$$k$$$ цветов. $$$k$$$-покраска является <span class="tex-font-style-bf">хорошей</span> тогда и только тогда, когда в графе не существует цикла, состоящего из ребер одного цвета.</p><p>Найдите хорошую $$$k$$$-покраску с минимально возможным значением $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — количество вершин и ребер, соответственно.</p><p>Следующие $$$m$$$ строк содержат описание ребер — по одному в строке. Каждое ребро задается парой целых чисел $$$u$$$ и $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — они обозначают ребро из вершины $$$u$$$ в вершину $$$v$$$.</p><p>Гарантируется, что каждая упорядоченная пара $$$(u, v)$$$ входит в список ребер не более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$k$$$ — количество цветов в $$$k$$$-покраске графа.</p><p>Во второй строке выведите $$$m$$$ целых чисел $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), где $$$c_i$$$ — цвет $$$i$$$-го ребра (ребра нумеруются в том порядке, в котором заданы во входных данных).</p><p>Если ответов несколько, выведите любой (но все равно надо минимизировать $$$k$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 1 3 3 4 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 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="6205fc7badfe481d3391b9d39294b7e5"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='6205fc7badfe481d3391b9d39294b7e5'>&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%2F1217%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='6205fc7badfe481d3391b9d39294b7e5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='6205fc7badfe481d3391b9d39294b7e5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='6205fc7badfe481d3391b9d39294b7e5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404646"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6205fc7badfe481d3391b9d39294b7e5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404646"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_375d455512ffc4d918eea3d1614e8ae8ff45ec7c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Вам дан ориентированный граф из $$$n$$$ вершин и $$$m$$$ ориентированных ребер. Гарантируется, что в нем нет ни петель, ни кратных ребер.</p><p>Определим $$$k$$$-покраску орграфа следующим образом: мы красим каждое ребро в один из $$$k$$$ цветов. $$$k$$$-покраска является <span class="tex-font-style-bf">хорошей</span> тогда и только тогда, когда в графе не существует цикла, состоящего из ребер одного цвета.</p><p>Найдите хорошую $$$k$$$-покраску с минимально возможным значением $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n \le 5000$$$, $$$1 \le m \le 5000$$$) — количество вершин и ребер, соответственно.</p><p>Следующие $$$m$$$ строк содержат описание ребер — по одному в строке. Каждое ребро задается парой целых чисел $$$u$$$ и $$$v$$$ ($$$1 \le u, v \le n$$$, $$$u \ne v$$$) — они обозначают ребро из вершины $$$u$$$ в вершину $$$v$$$.</p><p>Гарантируется, что каждая упорядоченная пара $$$(u, v)$$$ входит в список ребер не более одного раза.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите одно целое число $$$k$$$ — количество цветов в $$$k$$$-покраске графа.</p><p>Во второй строке выведите $$$m$$$ целых чисел $$$c_1, c_2, \dots, c_m$$$ ($$$1 \le c_i \le k$$$), где $$$c_i$$$ — цвет $$$i$$$-го ребра (ребра нумеруются в том порядке, в котором заданы во входных данных).</p><p>Если ответов несколько, выведите любой (но все равно надо минимизировать $$$k$$$).</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 5 1 2 1 3 3 4 2 4 1 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 3 1 2 2 3 3 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 1 1 2 </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 10:44: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:'81248546da0d5aae',t:'MTY5NjY2NDY4NC43MjAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u041a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u043a\u043e\u043d\u0441\u0442\u0440\u0443\u043a\u0442\u0438\u0432", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2100"]
1217E
1217
E
ru
E. Запросы суммы?
<div class="problem-statement"><div class="header"><div class="title">E. Запросы суммы?</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Введем определение <span class="tex-font-style-it">хорошего</span> мультимножества следующим образом. Выпишем сумму всех элементов мультимножества в виде десятичного числа. Если для каждого разряда существует хотя бы одно число из мультимножества, в котором такая же цифра, как и в полученной сумме, то мультимножество <span class="tex-font-style-it">хорошее</span>, иначе <span class="tex-font-style-it">плохое</span>.</p><p>Например, мультимножество $$$\{20, 300, 10001\}$$$ — <span class="tex-font-style-it">хорошее</span>, а мультимножество $$$\{20, 310, 10001\}$$$ — <span class="tex-font-style-it">плохое</span>:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5e05be78fead4148eb5458365bb42dad93ba1707.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Красным отмечены те числа и разряды, в которых те же цифры, что и в сумме. Сумма первого мультимножества равна $$$10321$$$, для каждого разряда есть необходимая цифра. Сумма второго мультимножества равна $$$10331$$$, и для второго с конца разряда не сушествует числа с такой же цифрой, что делает мультимножество <span class="tex-font-style-it">плохим</span>.</p><p>Вам дан массив из $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$.</p><p>Необходимо ответить на запросы к нему. Запросы могут быть двух типов:</p><ul> <li> $$$1~i~x$$$ — заменить $$$a_i$$$ на $$$x$$$; </li><li> $$$2~l~r$$$ — найти <span class="tex-font-style-bf"><span class="tex-font-style-it">плохое</span></span> подмножество мультимножества чисел $$$a_l, a_{l + 1}, \dots, a_r$$$ с минимальной суммой или сказать, что <span class="tex-font-style-it">плохих</span> подмножеств не существует. </li></ul><p>Обратите внимание, что пустое подмножество является <span class="tex-font-style-it">хорошим</span>.</p><p>Для каждого запроса второго типа выведите наименьшую сумму <span class="tex-font-style-it">плохого</span> подмножества. Выведите <span class="tex-font-style-tt">-1</span>, если не существует <span class="tex-font-style-it">плохого</span> подмножества.</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$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i &lt; 10^9$$$).</p><p>В каждой из следующих $$$m$$$ строк записан запрос одного из двух типов:</p><ul> <li> $$$1~i~x$$$ ($$$1 \le i \le n$$$, $$$1 \le x &lt; 10^9$$$) — заменить $$$a_i$$$ на $$$x$$$; </li><li> $$$2~l~r$$$ ($$$1 \le l \le r \le n$$$) — найти <span class="tex-font-style-bf"><span class="tex-font-style-it">плохое</span></span> подмножество мультимножества чисел $$$a_l, a_{l + 1}, \dots, a_r$$$ с минимальной суммой или сказать, что <span class="tex-font-style-it">плохих</span> подмножеств не существует. </li></ul><p>Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса второго типа выведите наименьшую сумму <span class="tex-font-style-it">плохого</span> подмножества. Выведите <span class="tex-font-style-tt">-1</span>, если не существует <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> 4 5 300 10001 20 20 2 1 3 1 1 310 2 1 3 2 3 3 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 330 -1 40 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все подмножества мультимножества $$$\{20, 300, 10001\}$$$ являются <span class="tex-font-style-it">хорошими</span>, поэтому ответ <span class="tex-font-style-tt">-1</span>.</p><p>Все возможные <span class="tex-font-style-it">плохие</span> подмножества в третьем запросе: $$$\{20, 310\}$$$ и $$$\{20, 310, 10001\}$$$. С меньшей суммой — $$$\{20, 310\}$$$. Обратите внимание, что требуется найти подмножество, а не подотрезок, поэтому выбранные элементы не обязательно будут стоять рядом в массиве.</p><p>В четвертом запросе есть только пустое подножество и подмножество $$$\{20\}$$$. Оба они <span class="tex-font-style-it">хорошие</span>.</p><p>В последнем запросе есть пустое подмножество и подмножества $$$\{20\}$$$, $$$\{20\}$$$ и $$$\{20, 20\}$$$. Только $$$\{20, 20\}$$$ — <span class="tex-font-style-it">плохое</span>, его сумма равна $$$40$$$. Обратите внимание, что требуется выбрать мультимножество, поэтому оно может включать в себя одинаковые элементы.</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="edfaba6747adb089aa2fa7cee749775c"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='edfaba6747adb089aa2fa7cee749775c'>&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%2F1217%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='edfaba6747adb089aa2fa7cee749775c'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='edfaba6747adb089aa2fa7cee749775c'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='edfaba6747adb089aa2fa7cee749775c'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404647"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='edfaba6747adb089aa2fa7cee749775c'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404647"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_7548c4feae229c7d2113ccbb27c81a596b1f6922"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Введем определение <span class="tex-font-style-it">хорошего</span> мультимножества следующим образом. Выпишем сумму всех элементов мультимножества в виде десятичного числа. Если для каждого разряда существует хотя бы одно число из мультимножества, в котором такая же цифра, как и в полученной сумме, то мультимножество <span class="tex-font-style-it">хорошее</span>, иначе <span class="tex-font-style-it">плохое</span>.</p><p>Например, мультимножество $$$\{20, 300, 10001\}$$$ — <span class="tex-font-style-it">хорошее</span>, а мультимножество $$$\{20, 310, 10001\}$$$ — <span class="tex-font-style-it">плохое</span>:</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/5e05be78fead4148eb5458365bb42dad93ba1707.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Красным отмечены те числа и разряды, в которых те же цифры, что и в сумме. Сумма первого мультимножества равна $$$10321$$$, для каждого разряда есть необходимая цифра. Сумма второго мультимножества равна $$$10331$$$, и для второго с конца разряда не сушествует числа с такой же цифрой, что делает мультимножество <span class="tex-font-style-it">плохим</span>.</p><p>Вам дан массив из $$$n$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$.</p><p>Необходимо ответить на запросы к нему. Запросы могут быть двух типов:</p><ul> <li> $$$1~i~x$$$ — заменить $$$a_i$$$ на $$$x$$$; </li><li> $$$2~l~r$$$ — найти <span class="tex-font-style-bf"><span class="tex-font-style-it">плохое</span></span> подмножество мультимножества чисел $$$a_l, a_{l + 1}, \dots, a_r$$$ с минимальной суммой или сказать, что <span class="tex-font-style-it">плохих</span> подмножеств не существует. </li></ul><p>Обратите внимание, что пустое подмножество является <span class="tex-font-style-it">хорошим</span>.</p><p>Для каждого запроса второго типа выведите наименьшую сумму <span class="tex-font-style-it">плохого</span> подмножества. Выведите <span class="tex-font-style-tt">-1</span>, если не существует <span class="tex-font-style-it">плохого</span> подмножества.</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$$$ целых чисел $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i &lt; 10^9$$$).</p><p>В каждой из следующих $$$m$$$ строк записан запрос одного из двух типов:</p><ul> <li> $$$1~i~x$$$ ($$$1 \le i \le n$$$, $$$1 \le x &lt; 10^9$$$) — заменить $$$a_i$$$ на $$$x$$$; </li><li> $$$2~l~r$$$ ($$$1 \le l \le r \le n$$$) — найти <span class="tex-font-style-bf"><span class="tex-font-style-it">плохое</span></span> подмножество мультимножества чисел $$$a_l, a_{l + 1}, \dots, a_r$$$ с минимальной суммой или сказать, что <span class="tex-font-style-it">плохих</span> подмножеств не существует. </li></ul><p>Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса второго типа выведите наименьшую сумму <span class="tex-font-style-it">плохого</span> подмножества. Выведите <span class="tex-font-style-tt">-1</span>, если не существует <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> 4 5 300 10001 20 20 2 1 3 1 1 310 2 1 3 2 3 3 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> -1 330 -1 40 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Все подмножества мультимножества $$$\{20, 300, 10001\}$$$ являются <span class="tex-font-style-it">хорошими</span>, поэтому ответ <span class="tex-font-style-tt">-1</span>.</p><p>Все возможные <span class="tex-font-style-it">плохие</span> подмножества в третьем запросе: $$$\{20, 310\}$$$ и $$$\{20, 310, 10001\}$$$. С меньшей суммой — $$$\{20, 310\}$$$. Обратите внимание, что требуется найти подмножество, а не подотрезок, поэтому выбранные элементы не обязательно будут стоять рядом в массиве.</p><p>В четвертом запросе есть только пустое подножество и подмножество $$$\{20\}$$$. Оба они <span class="tex-font-style-it">хорошие</span>.</p><p>В последнем запросе есть пустое подмножество и подмножества $$$\{20\}$$$, $$$\{20\}$$$ и $$$\{20, 20\}$$$. Только $$$\{20, 20\}$$$ — <span class="tex-font-style-it">плохое</span>, его сумма равна $$$40$$$. Обратите внимание, что требуется выбрать мультимножество, поэтому оно может включать в себя одинаковые элементы.</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 10:44: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:'8124854f2b269d9e',t:'MTY5NjY2NDY4Ni4wNjgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\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", "\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", "*2300"]
1217F
1217
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>256 мегабайт</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>Необходимо ответить на запросы к нему. Пусть $$$last$$$ будет ответом на предыдущий запрос второго типа (или $$$0$$$, если таких запросов еще не было). Тогда запросы следующие:</p><ul> <li> $$$1~x~y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) — добавить неориентированное ребро между вершинами $$$(x + last - 1)~mod~n + 1$$$ и $$$(y + last - 1)~mod~n + 1$$$, если такого в графе нет, а иначе удалить его; </li><li> $$$2~x~y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) — проверить, что существует путь между вершинами $$$(x + last - 1)~mod~n + 1$$$ и $$$(y + last - 1)~mod~n + 1$$$, который проходит только через существующие ребра, и выставить $$$last$$$ значение $$$1$$$, если есть, и $$$0$$$ иначе. </li></ul><p>Удачи!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — количество вершин в графе и количество запросов, соответственно.</p><p>В каждой из следующих $$$m$$$ строк записан запрос одного из выше приведенных типов. Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку, состоящую из символов '0' и '1'. $$$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> 5 9 1 1 2 1 1 3 2 3 2 1 2 4 2 3 4 1 2 4 2 3 4 1 1 3 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1010 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 9 1 1 2 1 2 3 1 3 1 2 1 3 1 3 2 2 2 3 1 1 2 2 1 2 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1101 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Преобразованные запросы из первого примера:</p><ul> <li> 1 1 2 </li><li> 1 1 3 </li><li> 2 3 2 </li><li> 1 3 5 </li><li> 2 4 5 </li><li> 1 2 4 </li><li> 2 3 4 </li><li> 1 2 4 </li><li> 2 5 4 </li></ul><p>Преобразованные запросы из второго примера:</p><ul> <li> 1 1 2 </li><li> 1 2 3 </li><li> 1 3 1 </li><li> 2 1 3 </li><li> 1 1 3 </li><li> 2 3 1 </li><li> 1 2 3 </li><li> 2 2 3 </li><li> 2 1 2 </li></ul></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b77961ea84c28e829cf665e3b3c845fb"/> <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="6b271513161365526ab6fa91fb0c4381cdcf4ba9"/> <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='b77961ea84c28e829cf665e3b3c845fb'>&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%2F1217%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='b77961ea84c28e829cf665e3b3c845fb'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1217">Educational Codeforces Round 72 (рейтинговый для Див. 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='b77961ea84c28e829cf665e3b3c845fb'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1217/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='b77961ea84c28e829cf665e3b3c845fb'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="404648"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b77961ea84c28e829cf665e3b3c845fb'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="404648"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69554" title="Educational Codeforces Round 72 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9302:9303" 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/69605" title="Разбор Educational Codeforces Round 72" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9308:9309" 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/1217">Задачи</a></li> <li><a href="/contest/1217/submit">Отослать</a></li> <li><a href="/contest/1217/my">Мои посылки</a></li> <li><a href="/contest/1217/status">Статус</a></li> <li><a href="/contest/1217/hacks">Взломы</a></li> <li><a href="/contest/1217/standings">Положение</a></li> <li><a href="/contest/1217/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_292beee4ebf262c6096105b661add765961f99f9"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</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>Необходимо ответить на запросы к нему. Пусть $$$last$$$ будет ответом на предыдущий запрос второго типа (или $$$0$$$, если таких запросов еще не было). Тогда запросы следующие:</p><ul> <li> $$$1~x~y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) — добавить неориентированное ребро между вершинами $$$(x + last - 1)~mod~n + 1$$$ и $$$(y + last - 1)~mod~n + 1$$$, если такого в графе нет, а иначе удалить его; </li><li> $$$2~x~y$$$ ($$$1 \le x, y \le n$$$, $$$x \ne y$$$) — проверить, что существует путь между вершинами $$$(x + last - 1)~mod~n + 1$$$ и $$$(y + last - 1)~mod~n + 1$$$, который проходит только через существующие ребра, и выставить $$$last$$$ значение $$$1$$$, если есть, и $$$0$$$ иначе. </li></ul><p>Удачи!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записаны два целых числа $$$n$$$ и $$$m$$$ ($$$2 \le n, m \le 2 \cdot 10^5$$$) — количество вершин в графе и количество запросов, соответственно.</p><p>В каждой из следующих $$$m$$$ строк записан запрос одного из выше приведенных типов. Гарантируется, что есть хотя бы один запрос второго типа.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите строку, состоящую из символов '0' и '1'. $$$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> 5 9 1 1 2 1 1 3 2 3 2 1 2 4 2 3 4 1 2 4 2 3 4 1 1 3 2 4 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1010 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 9 1 1 2 1 2 3 1 3 1 2 1 3 1 3 2 2 2 3 1 1 2 2 1 2 2 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1101 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Преобразованные запросы из первого примера:</p><ul> <li> 1 1 2 </li><li> 1 1 3 </li><li> 2 3 2 </li><li> 1 3 5 </li><li> 2 4 5 </li><li> 1 2 4 </li><li> 2 3 4 </li><li> 1 2 4 </li><li> 2 5 4 </li></ul><p>Преобразованные запросы из второго примера:</p><ul> <li> 1 1 2 </li><li> 1 2 3 </li><li> 1 3 1 </li><li> 2 1 3 </li><li> 1 1 3 </li><li> 2 3 1 </li><li> 1 2 3 </li><li> 2 2 3 </li><li> 2 1 2 </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 10:44: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:'8124855789d416db',t:'MTY5NjY2NDY4Ny40MTcwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\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", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0441\u043d\u043c", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2600"]
1218A
1218
A
ru
A. BubbleReactor
<div class="problem-statement"><div class="header"><div class="title">A. BubbleReactor</div><div class="time-limit"><div class="property-title">time limit per test</div>1.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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 in charge of the BubbleReactor. It consists of $$$N$$$ BubbleCores connected with $$$N$$$ lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.</p><p>Your task is to start the BubbleReactor by starting each BubbleCore. In order for a BubbleCore to be started it needs to be receiving power from a directly connected BubbleCore which is already started. However, you can kick-start one BubbleCore manually without needing power. It is guaranteed that all BubbleCores can be started.</p><p>Before the BubbleCore boot up procedure its potential is calculated as the number of BubbleCores it can power on (the number of inactive BubbleCores which are connected to it directly or with any number of inactive BubbleCores in between, itself included)</p><p>Start the BubbleReactor so that the sum of all BubbleCores' potentials is maximum.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one integer $$$N (3 \leq N \leq 15.000)$$$, the number of BubbleCores.</p><p>The following N lines contain two integers $$$U, V (0 \leq U \neq V &lt; N)$$$ denoting that there exists electrical wiring between BubbleCores $$$U$$$ and $$$V$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Single integer, the maximum sum of all BubbleCores' potentials.</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> 10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 51 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If we start by kickstarting BubbleCup 8 and then turning on cores 7, 2, 1, 3, 0, 9, 4, 5, 6 in that order we get potentials 10 + 9 + 8 + 7 + 6 + 5 + 1 + 3 + 1 + 1 = 51</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="c42107cb81e3c3245219ae7025d633ae"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='c42107cb81e3c3245219ae7025d633ae'>&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%2F1218%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='c42107cb81e3c3245219ae7025d633ae'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='c42107cb81e3c3245219ae7025d633ae'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='c42107cb81e3c3245219ae7025d633ae'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412333"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c42107cb81e3c3245219ae7025d633ae'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412333"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_33537ff740f36e7b9a02d4e61ac82329579fb1e2"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. BubbleReactor</div><div class="time-limit"><div class="property-title">time limit per test</div>1.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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 in charge of the BubbleReactor. It consists of $$$N$$$ BubbleCores connected with $$$N$$$ lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.</p><p>Your task is to start the BubbleReactor by starting each BubbleCore. In order for a BubbleCore to be started it needs to be receiving power from a directly connected BubbleCore which is already started. However, you can kick-start one BubbleCore manually without needing power. It is guaranteed that all BubbleCores can be started.</p><p>Before the BubbleCore boot up procedure its potential is calculated as the number of BubbleCores it can power on (the number of inactive BubbleCores which are connected to it directly or with any number of inactive BubbleCores in between, itself included)</p><p>Start the BubbleReactor so that the sum of all BubbleCores' potentials is maximum.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one integer $$$N (3 \leq N \leq 15.000)$$$, the number of BubbleCores.</p><p>The following N lines contain two integers $$$U, V (0 \leq U \neq V &lt; N)$$$ denoting that there exists electrical wiring between BubbleCores $$$U$$$ and $$$V$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Single integer, the maximum sum of all BubbleCores' potentials.</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> 10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 51 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If we start by kickstarting BubbleCup 8 and then turning on cores 7, 2, 1, 3, 0, 9, 4, 5, 6 in that order we get potentials 10 + 9 + 8 + 7 + 6 + 5 + 1 + 3 + 1 + 1 = 51</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 10:44: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:'812485601aba0c48',t:'MTY5NjY2NDY4OC44NTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u043f", "*2800"]
1218B
1218
B
ru
B. Guarding warehouses
<div class="problem-statement"><div class="header"><div class="title">B. Guarding warehouses</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Bob Bubblestrong just got a new job as security guard. Bob is now responsible for safety of a collection of warehouses, each containing the most valuable Bubble Cup assets - the high-quality bubbles. His task is to detect thieves inside the warehouses and call the police.</p><p>Looking from the sky, each warehouse has a shape of a convex polygon. Walls of no two warehouses intersect, and of course, none of the warehouses is built inside of another warehouse.</p><p>Little did the Bubble Cup bosses know how lazy Bob is and that he enjoys watching soap operas (he heard they are full of bubbles) from the coziness of his office. Instead of going from one warehouse to another to check if warehouses are secured, the plan Bob has is to monitor all the warehouses from the comfort of his office using the special X-ray goggles. The goggles have an infinite range, so a thief in any of the warehouses could easily be spotted.</p><p>However, the goggles promptly broke and the X-rays are now strong only enough to let Bob see through a single wall. Now, Bob would really appreciate if you could help him find out what is the total area inside of the warehouses monitored by the broken goggles, so that he could know how much area of the warehouses he needs to monitor in person.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ ($$$1$$$ $$$\leq$$$ $$$N$$$ $$$\leq$$$ $$$10^4$$$) – the number of warehouses.</p><p>The next $$$N$$$ lines describe the warehouses.</p><p>The first number of the line is integer $$$c_i$$$ ($$$3$$$ $$$\leq$$$ $$$c_i$$$ $$$\leq$$$ $$$10^4$$$) – the number corners in the $$$i^{th}$$$ warehouse, followed by $$$c_i$$$ pairs of integers. The $$$j^{th}$$$ pair is $$$(x_j, y_j)$$$ – the coordinates of the $$$j^{th}$$$ corner ($$$|x_j|$$$, $$$|y_j|$$$ $$$\leq$$$ $$$3 * 10^4$$$). The corners are listed in the clockwise order. The total number of corners in all the warehouses is at most $$$5 * 10^4$$$.</p><p>Bob's office is positioned at the point with coordinates $$$(0, 0)$$$. The office is not contained within any of the warehouses.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print a single line containing a single decimal number accurate to at least four decimal places – the total area of the warehouses Bob can monitor using the broken X-ray goggles.</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> 5 4 1 1 1 3 3 3 3 1 4 4 3 6 2 6 0 4 0 6 -5 3 -4 4 -3 4 -2 3 -3 2 -4 2 3 0 -1 1 -3 -1 -3 4 1 -4 1 -6 -1 -6 -1 -4 </pre></div><div class="output"><div class="title">Output</div><pre> 13.333333333333 </pre></div></div></div><div class="note"><div class="section-title">Note</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e4eaf064e46dff00c8576749b9c8ec9cac56c545.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p>Areas monitored by the X-ray goggles are colored green and areas not monitored by the goggles are colored red.</p><p>The warehouses $$$ABCD$$$, $$$IJK$$$ and $$$LMNOPQ$$$ are completely monitored using the googles.</p><p>The warehouse $$$EFGH$$$ is partially monitored using the goggles: part $$$EFW$$$ is not monitored because to monitor each point inside it, the X-rays must go through two walls of warehouse $$$ABCD$$$.</p><p>The warehouse $$$RUTS$$$ is not monitored from the Bob's office, because there are two walls of the warehouse $$$IJK$$$ between Bob's office and each point in $$$RUTS$$$.</p><p>The total area monitored by the goggles is $$$P$$$ = $$$P_{ABCD}$$$ + $$$P_{FGHW}$$$ + $$$P_{IJK}$$$ + $$$P_{LMNOPQ}$$$ = $$$4$$$ + $$$3.333333333333$$$ + $$$2$$$ + $$$4$$$ = $$$13.333333333333$$$.</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="1a23dcd7cae61e64ab91c51d72b4cfe8"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='1a23dcd7cae61e64ab91c51d72b4cfe8'>&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%2F1218%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='1a23dcd7cae61e64ab91c51d72b4cfe8'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='1a23dcd7cae61e64ab91c51d72b4cfe8'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='1a23dcd7cae61e64ab91c51d72b4cfe8'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412334"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='1a23dcd7cae61e64ab91c51d72b4cfe8'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412334"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8f1d97785a997e7e4b814d5594a3431330c416e0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Guarding warehouses</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Bob Bubblestrong just got a new job as security guard. Bob is now responsible for safety of a collection of warehouses, each containing the most valuable Bubble Cup assets - the high-quality bubbles. His task is to detect thieves inside the warehouses and call the police.</p><p>Looking from the sky, each warehouse has a shape of a convex polygon. Walls of no two warehouses intersect, and of course, none of the warehouses is built inside of another warehouse.</p><p>Little did the Bubble Cup bosses know how lazy Bob is and that he enjoys watching soap operas (he heard they are full of bubbles) from the coziness of his office. Instead of going from one warehouse to another to check if warehouses are secured, the plan Bob has is to monitor all the warehouses from the comfort of his office using the special X-ray goggles. The goggles have an infinite range, so a thief in any of the warehouses could easily be spotted.</p><p>However, the goggles promptly broke and the X-rays are now strong only enough to let Bob see through a single wall. Now, Bob would really appreciate if you could help him find out what is the total area inside of the warehouses monitored by the broken goggles, so that he could know how much area of the warehouses he needs to monitor in person.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ ($$$1$$$ $$$\leq$$$ $$$N$$$ $$$\leq$$$ $$$10^4$$$) – the number of warehouses.</p><p>The next $$$N$$$ lines describe the warehouses.</p><p>The first number of the line is integer $$$c_i$$$ ($$$3$$$ $$$\leq$$$ $$$c_i$$$ $$$\leq$$$ $$$10^4$$$) – the number corners in the $$$i^{th}$$$ warehouse, followed by $$$c_i$$$ pairs of integers. The $$$j^{th}$$$ pair is $$$(x_j, y_j)$$$ – the coordinates of the $$$j^{th}$$$ corner ($$$|x_j|$$$, $$$|y_j|$$$ $$$\leq$$$ $$$3 * 10^4$$$). The corners are listed in the clockwise order. The total number of corners in all the warehouses is at most $$$5 * 10^4$$$.</p><p>Bob's office is positioned at the point with coordinates $$$(0, 0)$$$. The office is not contained within any of the warehouses.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print a single line containing a single decimal number accurate to at least four decimal places – the total area of the warehouses Bob can monitor using the broken X-ray goggles.</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> 5 4 1 1 1 3 3 3 3 1 4 4 3 6 2 6 0 4 0 6 -5 3 -4 4 -3 4 -2 3 -3 2 -4 2 3 0 -1 1 -3 -1 -3 4 1 -4 1 -6 -1 -6 -1 -4 </pre></div><div class="output"><div class="title">Output</div><pre> 13.333333333333 </pre></div></div></div><div class="note"><div class="section-title">Note</div><center> <img class="tex-graphics" src="https://espresso.codeforces.com/e4eaf064e46dff00c8576749b9c8ec9cac56c545.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p>Areas monitored by the X-ray goggles are colored green and areas not monitored by the goggles are colored red.</p><p>The warehouses $$$ABCD$$$, $$$IJK$$$ and $$$LMNOPQ$$$ are completely monitored using the googles.</p><p>The warehouse $$$EFGH$$$ is partially monitored using the goggles: part $$$EFW$$$ is not monitored because to monitor each point inside it, the X-rays must go through two walls of warehouse $$$ABCD$$$.</p><p>The warehouse $$$RUTS$$$ is not monitored from the Bob's office, because there are two walls of the warehouse $$$IJK$$$ between Bob's office and each point in $$$RUTS$$$.</p><p>The total area monitored by the goggles is $$$P$$$ = $$$P_{ABCD}$$$ + $$$P_{FGHW}$$$ + $$$P_{IJK}$$$ + $$$P_{LMNOPQ}$$$ = $$$4$$$ + $$$3.333333333333$$$ + $$$2$$$ + $$$4$$$ = $$$13.333333333333$$$.</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 10:44: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:'8124856919987b37',t:'MTY5NjY2NDY5MC4yMjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*3000"]
1218C
1218
C
ru
C. Jumping Transformers
<div class="problem-statement"><div class="header"><div class="title">C. Jumping Transformers</div><div class="time-limit"><div class="property-title">time limit per test</div>4 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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, the mighty Blackout, are standing in the upper-left $$$(0,0)$$$ corner of $$$N$$$x$$$M$$$ matrix. You must move either right or down each second. </p><p>There are $$$K$$$ transformers jumping around the matrix in the following way. Each transformer starts jumping from position $$$(x,y)$$$, at time $$$t$$$, and jumps to the next position each second. The $$$x$$$-axes grows downwards, and $$$y$$$-axes grows to the right. The order of jumping positions is defined as $$${(x,y),(x+d,y-d),(x+d,y),(x,y+d)}$$$, and is periodic. Before time $$$t$$$ transformer is not in the matrix.</p><p>You want to arrive to the bottom-right corner $$$(N-1,M-1)$$$, while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.</p><p>After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first line, integers $$$N$$$,$$$M$$$ ($$$1 \leq N, M \leq 500$$$), representing size of the matrix, and $$$K$$$ ($$$0 \leq K \leq 5*10^5$$$) , the number of jumping transformers.</p><p>In next $$$K$$$ lines, for each transformer, numbers $$$x$$$, $$$y$$$, $$$d$$$ ($$$d \geq 1$$$), $$$t$$$ ($$$0 \leq t \leq N+M-2$$$), and $$$e$$$ ($$$0 \leq e \leq 10^9$$$), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.</p><p>It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.</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 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 </pre></div><div class="output"><div class="title">Output</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.</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="18da207cc369d6e1c821ec76ab6243cd"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='18da207cc369d6e1c821ec76ab6243cd'>&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%2F1218%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='18da207cc369d6e1c821ec76ab6243cd'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='18da207cc369d6e1c821ec76ab6243cd'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='18da207cc369d6e1c821ec76ab6243cd'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412335"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='18da207cc369d6e1c821ec76ab6243cd'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412335"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0f0f3fbed36782da8a3cee0fcb167c1cb1ff9a18"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Jumping Transformers</div><div class="time-limit"><div class="property-title">time limit per test</div>4 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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, the mighty Blackout, are standing in the upper-left $$$(0,0)$$$ corner of $$$N$$$x$$$M$$$ matrix. You must move either right or down each second. </p><p>There are $$$K$$$ transformers jumping around the matrix in the following way. Each transformer starts jumping from position $$$(x,y)$$$, at time $$$t$$$, and jumps to the next position each second. The $$$x$$$-axes grows downwards, and $$$y$$$-axes grows to the right. The order of jumping positions is defined as $$${(x,y),(x+d,y-d),(x+d,y),(x,y+d)}$$$, and is periodic. Before time $$$t$$$ transformer is not in the matrix.</p><p>You want to arrive to the bottom-right corner $$$(N-1,M-1)$$$, while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.</p><p>After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first line, integers $$$N$$$,$$$M$$$ ($$$1 \leq N, M \leq 500$$$), representing size of the matrix, and $$$K$$$ ($$$0 \leq K \leq 5*10^5$$$) , the number of jumping transformers.</p><p>In next $$$K$$$ lines, for each transformer, numbers $$$x$$$, $$$y$$$, $$$d$$$ ($$$d \geq 1$$$), $$$t$$$ ($$$0 \leq t \leq N+M-2$$$), and $$$e$$$ ($$$0 \leq e \leq 10^9$$$), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.</p><p>It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.</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 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 </pre></div><div class="output"><div class="title">Output</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.</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 10:44: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:'81248571ad977b23',t:'MTY5NjY2NDY5MS41NjEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2600"]
1218D
1218
D
ru
D. Xor Spanning Tree
<div class="problem-statement"><div class="header"><div class="title">D. Xor Spanning Tree</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of $$$N$$$ planets. Between them, there are $$$M$$$ bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached using these wormholes. It is also guaranteed that no wormhole connects planet to itself and that no two different wormholes connect same pair of planets. </p><p>We call a path that begins at one planet, visits other planets and each of them at most once and returns to starting point a <span class="tex-font-style-it">tour</span>. Interplanetary Safety Regulations guarantee that each planet belongs to at most one <span class="tex-font-style-it">tour</span> and that there are at most $$$42$$$ <span class="tex-font-style-it">tours</span>.</p><p>After many eons of usage, wormholes need to be repaired and each wormhole has the cost $$$W_{i}$$$ which needs to be payed for reparation. Unfortunately, the Senate of Bubbleland is short on budget. Therefore, they have decided only to fix as many wormholes as they need in order to have all planets reachable from capital and to pay as little money as they have to for this repair. However the way in which the Senate calculates the cost is different. Cost of the set of reparations is binary xor of costs of each individual reparation, that is if reparations to be made have costs $$$A_{1},A_{2},...,A_{k}$$$, the cost of entire set is $$$A_{1} \oplus A_{2} \oplus ... \oplus A_{k}$$$.</p><p>Now the Senate would like to know how much money do they have to pay and also the number of different ways to achieve that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line of input contains two numbers $$$N (1 \leq N \leq 100.000)$$$, the number of planets and $$$M (1 \leq M \leq 100.041)$$$, the number of wormholes. Following $$$M$$$ lines contain three numbers $$$U, V (1 \leq U \neq V \leq N)$$$ and $$$W (1 \leq W \leq 100.000)$$$, meaning that there exists a wormhole connecting planets $$$U$$$ and $$$V$$$, with repair cost of $$$W$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output two numbers, the smallest possible cost of entire reparation and the number of different valid reparations with that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</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 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>We can repair wormholes $$$1$$$,$$$2$$$,$$$3$$$,$$$5$$$ and $$$6$$$, paying $$$5 \oplus 1\oplus 2 \oplus 3 \oplus 4=1$$$, one can check that this is the cheapest repair in which all of the planets are connected and the only valid repair with that cost.</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="c897617d32adfa8e49ebe406cb0e46d7"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='c897617d32adfa8e49ebe406cb0e46d7'>&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%2F1218%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='c897617d32adfa8e49ebe406cb0e46d7'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='c897617d32adfa8e49ebe406cb0e46d7'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='c897617d32adfa8e49ebe406cb0e46d7'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412336"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c897617d32adfa8e49ebe406cb0e46d7'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412336"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_dc8a959dcecdc8dca5f6ec0458a8f5ed9842f3bc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Xor Spanning Tree</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of $$$N$$$ planets. Between them, there are $$$M$$$ bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached using these wormholes. It is also guaranteed that no wormhole connects planet to itself and that no two different wormholes connect same pair of planets. </p><p>We call a path that begins at one planet, visits other planets and each of them at most once and returns to starting point a <span class="tex-font-style-it">tour</span>. Interplanetary Safety Regulations guarantee that each planet belongs to at most one <span class="tex-font-style-it">tour</span> and that there are at most $$$42$$$ <span class="tex-font-style-it">tours</span>.</p><p>After many eons of usage, wormholes need to be repaired and each wormhole has the cost $$$W_{i}$$$ which needs to be payed for reparation. Unfortunately, the Senate of Bubbleland is short on budget. Therefore, they have decided only to fix as many wormholes as they need in order to have all planets reachable from capital and to pay as little money as they have to for this repair. However the way in which the Senate calculates the cost is different. Cost of the set of reparations is binary xor of costs of each individual reparation, that is if reparations to be made have costs $$$A_{1},A_{2},...,A_{k}$$$, the cost of entire set is $$$A_{1} \oplus A_{2} \oplus ... \oplus A_{k}$$$.</p><p>Now the Senate would like to know how much money do they have to pay and also the number of different ways to achieve that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line of input contains two numbers $$$N (1 \leq N \leq 100.000)$$$, the number of planets and $$$M (1 \leq M \leq 100.041)$$$, the number of wormholes. Following $$$M$$$ lines contain three numbers $$$U, V (1 \leq U \neq V \leq N)$$$ and $$$W (1 \leq W \leq 100.000)$$$, meaning that there exists a wormhole connecting planets $$$U$$$ and $$$V$$$, with repair cost of $$$W$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output two numbers, the smallest possible cost of entire reparation and the number of different valid reparations with that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</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 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>We can repair wormholes $$$1$$$,$$$2$$$,$$$3$$$,$$$5$$$ and $$$6$$$, paying $$$5 \oplus 1\oplus 2 \oplus 3 \oplus 4=1$$$, one can check that this is the cheapest repair in which all of the planets are connected and the only valid repair with that cost.</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 10:44: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:'81248579ea939d46',t:'MTY5NjY2NDY5My4wMDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0413\u0440\u0430\u0444\u044b", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0433\u0440\u0430\u0444\u044b", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2400"]
1218E
1218
E
ru
E. Product Tuples
<div class="problem-statement"><div class="header"><div class="title">E. Product Tuples</div><div class="time-limit"><div class="property-title">time limit per test</div>8 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>While roaming the mystic areas of Stonefalls, in order to drop legendary loot, an adventurer was given a quest as follows. He was given an array $$$A = {a_1,a_2,...,a_N }$$$ of length $$$N$$$, and a number $$$K$$$.</p><p>Define array $$$B$$$ as $$$B(q, A) = $$$ { $$$q-a_1, q-a_2, ..., q-a_N$$$ }. Define function $$$F$$$ as $$$F(B,K)$$$ being sum of products of all $$$K$$$-tuples of elements in array $$$B$$$. For example, if the array $$$B$$$ is $$$[2,3,4,5]$$$, and with $$$K=3$$$, sum of products of all 3-tuples is $$$$$$F(B, 3) = 2*3*4+2*3*5+3*4*5+2*4*5$$$$$$</p><p>He was then given a number Q, number of queries of two types: </p><ul> <li> Type 1: Given $$$q$$$, $$$i$$$, and $$$d$$$ calculate $$$F(B(q, A), K)$$$ where we make change to initial array as $$$A[i] = d$$$. </li><li> Type 2: Given $$$q$$$, $$$L$$$, $$$R$$$, and $$$d$$$ calculate $$$F(B(q, A), K)$$$ where we make change to initial array as $$$A[i] = A[i] + d$$$ for all $$$i$$$ in range $$$[L, R]$$$ inclusive. </li></ul><p>All changes are temporarily made to initial array, and don't propagate to following queries. Help the adventurer calculate the answer to a quest, and finally get that loot!</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first two lines, numbers $$$N$$$ ($$$1 \leq N \leq 2*10^4$$$) and $$$K$$$ ($$$1 \leq K \leq N$$$), the length of initial array $$$A$$$, and tuple size, followed by $$$a_1,a_2,a_3,…,a_N$$$ ($$$0 \leq a_i \leq 10^9$$$) , elements of array $$$A$$$, in the next line. Then follows number $$$Q$$$ ($$$Q \leq 10$$$), number of queries. In the next $$$Q$$$ lines come queries of the form: </p><ul> <li> 1 q i d, for type 1, </li><li> 2 q L R d, for type 2, </li></ul><p>as explained above ($$$0 \leq q, d \leq 10^9, 1 \leq i,L,R \leq N$$$)</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print $$$Q$$$ lines, the answers to queries, modulo $$$998244353$$$.</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> 5 2 1 2 3 4 5 3 1 6 1 1 1 6 5 2 2 6 2 3 1 </pre></div><div class="output"><div class="title">Output</div><pre> 85 127 63 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first query array A = [1, 2, 3, 4, 5], B = [5, 4, 3, 2, 1], sum of products of 2-tuples = 85.</p><p>In second query array A = [1, 2, 3, 4, 2], B = [5, 4, 3, 2, 4], sum of products of 2-tuples = 127</p><p>In third query array A = [1, 3, 4, 4, 5], B = [5, 3, 2, 2, 1], sum of products of 2-tuples = 63</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="b2d4fe214146f89e3c2b26476c8da54e"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='b2d4fe214146f89e3c2b26476c8da54e'>&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%2F1218%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='b2d4fe214146f89e3c2b26476c8da54e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='b2d4fe214146f89e3c2b26476c8da54e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b2d4fe214146f89e3c2b26476c8da54e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412337"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b2d4fe214146f89e3c2b26476c8da54e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412337"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_8ccc0feeab0fe713ed19bb15b192337c5fd9785b"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Product Tuples</div><div class="time-limit"><div class="property-title">time limit per test</div>8 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>While roaming the mystic areas of Stonefalls, in order to drop legendary loot, an adventurer was given a quest as follows. He was given an array $$$A = {a_1,a_2,...,a_N }$$$ of length $$$N$$$, and a number $$$K$$$.</p><p>Define array $$$B$$$ as $$$B(q, A) = $$$ { $$$q-a_1, q-a_2, ..., q-a_N$$$ }. Define function $$$F$$$ as $$$F(B,K)$$$ being sum of products of all $$$K$$$-tuples of elements in array $$$B$$$. For example, if the array $$$B$$$ is $$$[2,3,4,5]$$$, and with $$$K=3$$$, sum of products of all 3-tuples is $$$$$$F(B, 3) = 2*3*4+2*3*5+3*4*5+2*4*5$$$$$$</p><p>He was then given a number Q, number of queries of two types: </p><ul> <li> Type 1: Given $$$q$$$, $$$i$$$, and $$$d$$$ calculate $$$F(B(q, A), K)$$$ where we make change to initial array as $$$A[i] = d$$$. </li><li> Type 2: Given $$$q$$$, $$$L$$$, $$$R$$$, and $$$d$$$ calculate $$$F(B(q, A), K)$$$ where we make change to initial array as $$$A[i] = A[i] + d$$$ for all $$$i$$$ in range $$$[L, R]$$$ inclusive. </li></ul><p>All changes are temporarily made to initial array, and don't propagate to following queries. Help the adventurer calculate the answer to a quest, and finally get that loot!</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first two lines, numbers $$$N$$$ ($$$1 \leq N \leq 2*10^4$$$) and $$$K$$$ ($$$1 \leq K \leq N$$$), the length of initial array $$$A$$$, and tuple size, followed by $$$a_1,a_2,a_3,…,a_N$$$ ($$$0 \leq a_i \leq 10^9$$$) , elements of array $$$A$$$, in the next line. Then follows number $$$Q$$$ ($$$Q \leq 10$$$), number of queries. In the next $$$Q$$$ lines come queries of the form: </p><ul> <li> 1 q i d, for type 1, </li><li> 2 q L R d, for type 2, </li></ul><p>as explained above ($$$0 \leq q, d \leq 10^9, 1 \leq i,L,R \leq N$$$)</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print $$$Q$$$ lines, the answers to queries, modulo $$$998244353$$$.</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> 5 2 1 2 3 4 5 3 1 6 1 1 1 6 5 2 2 6 2 3 1 </pre></div><div class="output"><div class="title">Output</div><pre> 85 127 63 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first query array A = [1, 2, 3, 4, 5], B = [5, 4, 3, 2, 1], sum of products of 2-tuples = 85.</p><p>In second query array A = [1, 2, 3, 4, 2], B = [5, 4, 3, 2, 4], sum of products of 2-tuples = 127</p><p>In third query array A = [1, 3, 4, 4, 5], B = [5, 3, 2, 2, 1], sum of products of 2-tuples = 63</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 10:44: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:'81248582f9829da8',t:'MTY5NjY2NDY5NC4yODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u044b\u0441\u0442\u0440\u043e\u0435 \u043f\u0440\u0435\u043e\u0431\u0440\u0430\u0437\u043e\u0432\u0430\u043d\u0438\u0435 \u0424\u0443\u0440\u044c\u0435", "\u0420\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u043f\u0444", "\u0440\u0430\u0437\u0434\u0435\u043b\u044f\u0439 \u0438 \u0432\u043b\u0430\u0441\u0442\u0432\u0443\u0439", "*2500"]
1218F
1218
F
ru
F. Workout plan
<div class="problem-statement"><div class="header"><div class="title">F. Workout plan</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $$$X[i]$$$ grams on day $$$i$$$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $$$A$$$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $$$C[i]$$$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $$$K$$$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first one contains two integer numbers, integers $$$N$$$ $$$(1 \leq N \leq 10^5)$$$ and $$$K$$$ $$$(1 \leq K \leq 10^5)$$$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $$$N$$$ integer numbers $$$X[i]$$$ $$$(1 \leq X[i] \leq 10^9)$$$ separated by a single space representing how many grams Alan wants to lift on day $$$i$$$. The third line contains one integer number $$$A$$$ $$$(1 \leq A \leq 10^9)$$$ representing permanent performance gains from a single drink. The last line contains $$$N$$$ integer numbers $$$C[i]$$$ $$$(1 \leq C[i] \leq 10^9)$$$ , representing cost of performance booster drink in the gym he visits on day $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -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> 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> 5 </pre></div><div class="input"><div class="title">Input</div><pre> 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 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="7ee75944b646de13bf5403da209226d3"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='7ee75944b646de13bf5403da209226d3'>&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%2F1218%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='7ee75944b646de13bf5403da209226d3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='7ee75944b646de13bf5403da209226d3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='7ee75944b646de13bf5403da209226d3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412338"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='7ee75944b646de13bf5403da209226d3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412338"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1537bb7c8ec054707f80c8a748ea9aa0b63f11a0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Workout plan</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $$$X[i]$$$ grams on day $$$i$$$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $$$A$$$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $$$C[i]$$$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $$$K$$$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first one contains two integer numbers, integers $$$N$$$ $$$(1 \leq N \leq 10^5)$$$ and $$$K$$$ $$$(1 \leq K \leq 10^5)$$$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $$$N$$$ integer numbers $$$X[i]$$$ $$$(1 \leq X[i] \leq 10^9)$$$ separated by a single space representing how many grams Alan wants to lift on day $$$i$$$. The third line contains one integer number $$$A$$$ $$$(1 \leq A \leq 10^9)$$$ representing permanent performance gains from a single drink. The last line contains $$$N$$$ integer numbers $$$C[i]$$$ $$$(1 \leq C[i] \leq 10^9)$$$ , representing cost of performance booster drink in the gym he visits on day $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -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> 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> 5 </pre></div><div class="input"><div class="title">Input</div><pre> 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 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 10:44: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:'8124858cea8b3a55',t:'MTY5NjY2NDY5NS45NTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"]
1218G
1218
G
ru
G. Alpha planetary system
<div class="problem-statement"><div class="header"><div class="title">G. Alpha planetary system</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>Three planets $$$X$$$, $$$Y$$$ and $$$Z$$$ within the Alpha planetary system are inhabited with an advanced civilization. The spaceports of these planets are connected by interplanetary space shuttles. The flight scheduler should decide between $$$1$$$, $$$2$$$ and $$$3$$$ return flights for every existing space shuttle connection. Since the residents of Alpha are strong opponents of the symmetry, there is a strict rule that any two of the spaceports connected by a shuttle must have a different number of flights. </p><p>For every pair of connected spaceports, your goal is to propose a number $$$1$$$, $$$2$$$ or $$$3$$$ for each shuttle flight, so that for every two connected spaceports the overall number of flights differs. </p><p>You may assume that:</p><p>1) Every planet has at least one spaceport </p><p>2) There exist only shuttle flights between spaceports of different planets </p><p>3) For every two spaceports there is a series of shuttle flights enabling traveling between them</p><p>4) Spaceports are not connected by more than one shuttle</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first row of the input is the integer number $$$N$$$ $$$(3 \leq N \leq 100 000)$$$, representing overall number of spaceports. The second row is the integer number $$$M$$$ $$$(2 \leq M \leq 100 000)$$$ representing number of shuttle flight connections. </p><p>Third row contains $$$N$$$ characters from the set $$$\{X, Y, Z\}$$$. Letter on $$$I^{th}$$$ position indicates on which planet is situated spaceport $$$I$$$. For example, "XYYXZZ" indicates that the spaceports $$$0$$$ and $$$3$$$ are located at planet $$$X$$$, spaceports $$$1$$$ and $$$2$$$ are located at $$$Y$$$, and spaceports $$$4$$$ and $$$5$$$ are at $$$Z$$$. </p><p>Starting from the fourth row, every row contains two integer numbers separated by a whitespace. These numbers are natural numbers smaller than $$$N$$$ and indicate the numbers of the spaceports that are connected. For example, "$$$12\ 15$$$" indicates that there is a shuttle flight between spaceports $$$12$$$ and $$$15$$$. </p></div><div class="output-specification"><div class="section-title">Output</div><p>The same representation of shuttle flights in separate rows as in the input, but also containing a third number from the set $$$\{1, 2, 3\}$$$ standing for the number of shuttle flights between these spaceports.</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> 10 15 XXXXYYYZZZ 0 4 0 5 0 6 4 1 4 8 1 7 1 9 7 2 7 5 5 3 6 2 6 9 8 2 8 3 9 3 </pre></div><div class="output"><div class="title">Output</div><pre> 0 4 2 0 5 2 0 6 2 4 1 1 4 8 1 1 7 2 1 9 3 7 2 2 7 5 1 5 3 1 6 2 1 6 9 1 8 2 3 8 3 1 9 3 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="6a07fd1deef2f6a4d38c30af8a23a0c3"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='6a07fd1deef2f6a4d38c30af8a23a0c3'>&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%2F1218%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='6a07fd1deef2f6a4d38c30af8a23a0c3'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='6a07fd1deef2f6a4d38c30af8a23a0c3'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='6a07fd1deef2f6a4d38c30af8a23a0c3'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412339"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6a07fd1deef2f6a4d38c30af8a23a0c3'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412339"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3876c3b10524b10b25dd7e391bc59f51cccfbffa"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Alpha planetary system</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>Three planets $$$X$$$, $$$Y$$$ and $$$Z$$$ within the Alpha planetary system are inhabited with an advanced civilization. The spaceports of these planets are connected by interplanetary space shuttles. The flight scheduler should decide between $$$1$$$, $$$2$$$ and $$$3$$$ return flights for every existing space shuttle connection. Since the residents of Alpha are strong opponents of the symmetry, there is a strict rule that any two of the spaceports connected by a shuttle must have a different number of flights. </p><p>For every pair of connected spaceports, your goal is to propose a number $$$1$$$, $$$2$$$ or $$$3$$$ for each shuttle flight, so that for every two connected spaceports the overall number of flights differs. </p><p>You may assume that:</p><p>1) Every planet has at least one spaceport </p><p>2) There exist only shuttle flights between spaceports of different planets </p><p>3) For every two spaceports there is a series of shuttle flights enabling traveling between them</p><p>4) Spaceports are not connected by more than one shuttle</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first row of the input is the integer number $$$N$$$ $$$(3 \leq N \leq 100 000)$$$, representing overall number of spaceports. The second row is the integer number $$$M$$$ $$$(2 \leq M \leq 100 000)$$$ representing number of shuttle flight connections. </p><p>Third row contains $$$N$$$ characters from the set $$$\{X, Y, Z\}$$$. Letter on $$$I^{th}$$$ position indicates on which planet is situated spaceport $$$I$$$. For example, &quot;XYYXZZ&quot; indicates that the spaceports $$$0$$$ and $$$3$$$ are located at planet $$$X$$$, spaceports $$$1$$$ and $$$2$$$ are located at $$$Y$$$, and spaceports $$$4$$$ and $$$5$$$ are at $$$Z$$$. </p><p>Starting from the fourth row, every row contains two integer numbers separated by a whitespace. These numbers are natural numbers smaller than $$$N$$$ and indicate the numbers of the spaceports that are connected. For example, &quot;$$$12\ 15$$$&quot; indicates that there is a shuttle flight between spaceports $$$12$$$ and $$$15$$$. </p></div><div class="output-specification"><div class="section-title">Output</div><p>The same representation of shuttle flights in separate rows as in the input, but also containing a third number from the set $$$\{1, 2, 3\}$$$ standing for the number of shuttle flights between these spaceports.</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> 10 15 XXXXYYYZZZ 0 4 0 5 0 6 4 1 4 8 1 7 1 9 7 2 7 5 5 3 6 2 6 9 8 2 8 3 9 3 </pre></div><div class="output"><div class="title">Output</div><pre> 0 4 2 0 5 2 0 6 2 4 1 1 4 8 1 1 7 2 1 9 3 7 2 2 7 5 1 5 3 1 6 2 1 6 9 1 8 2 3 8 3 1 9 3 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 10:44: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:'812485955e419d6f',t:'MTY5NjY2NDY5Ny4yNDMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\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", "*3000"]
1218H
1218
H
ru
H. Function Composition
<div class="problem-statement"><div class="header"><div class="title">H. Function Composition</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.</p><p>First, let us define several things. We define function $$$F$$$ on the array $$$A$$$ such that $$$F(i, 1) = A[i]$$$ and $$$F(i, m) = A[F(i, m - 1)]$$$ for $$$m &gt; 1$$$. In other words, value $$$F(i, m)$$$ represents composition $$$A[...A[i]]$$$ applied $$$m$$$ times.</p><p>You are given an array of length $$$N$$$ with non-negative integers. You are expected to give an answer on $$$Q$$$ queries. Each query consists of two numbers – $$$m$$$ and $$$y$$$. For each query determine how many $$$x$$$ exist such that $$$F(x,m) = y$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ $$$(1 \leq N \leq 2 \cdot 10^5)$$$ – the size of the array $$$A$$$. The next line contains $$$N$$$ non-negative integers – the array $$$A$$$ itself $$$(1 \leq A_i \leq N)$$$. The next line contains one integer $$$Q$$$ $$$(1 \leq Q \leq 10^5)$$$ – the number of queries. Each of the next $$$Q$$$ lines contain two integers $$$m$$$ and $$$y$$$ $$$(1 \leq m \leq 10^{18}, 1\leq y \leq N)$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output exactly $$$Q$$$ lines with a single integer in each that represent the solution. Output the solutions in the order the queries were asked in.</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> 10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8 </pre></div><div class="output"><div class="title">Output</div><pre> 3 0 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>For the first query we can notice that $$$F(3, 10) = 1,\ F(9, 10) = 1$$$ and $$$F(10, 10) = 1$$$.</p><p>For the second query no $$$x$$$ satisfies condition $$$F(x, 5) = 7$$$.</p><p>For the third query $$$F(5, 10) = 6$$$ holds.</p><p>For the fourth query $$$F(3, 1) = 1.$$$</p><p>For the fifth query no $$$x$$$ satisfies condition $$$F(x, 10) = 8$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="b8df8813720520353f40c528753170b9"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='b8df8813720520353f40c528753170b9'>&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%2F1218%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='b8df8813720520353f40c528753170b9'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='b8df8813720520353f40c528753170b9'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='b8df8813720520353f40c528753170b9'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412340"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b8df8813720520353f40c528753170b9'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412340"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5326b4b7a870e2e5f82cc5361948898e113a3a26"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Function Composition</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.</p><p>First, let us define several things. We define function $$$F$$$ on the array $$$A$$$ such that $$$F(i, 1) = A[i]$$$ and $$$F(i, m) = A[F(i, m - 1)]$$$ for $$$m &gt; 1$$$. In other words, value $$$F(i, m)$$$ represents composition $$$A[...A[i]]$$$ applied $$$m$$$ times.</p><p>You are given an array of length $$$N$$$ with non-negative integers. You are expected to give an answer on $$$Q$$$ queries. Each query consists of two numbers – $$$m$$$ and $$$y$$$. For each query determine how many $$$x$$$ exist such that $$$F(x,m) = y$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ $$$(1 \leq N \leq 2 \cdot 10^5)$$$ – the size of the array $$$A$$$. The next line contains $$$N$$$ non-negative integers – the array $$$A$$$ itself $$$(1 \leq A_i \leq N)$$$. The next line contains one integer $$$Q$$$ $$$(1 \leq Q \leq 10^5)$$$ – the number of queries. Each of the next $$$Q$$$ lines contain two integers $$$m$$$ and $$$y$$$ $$$(1 \leq m \leq 10^{18}, 1\leq y \leq N)$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output exactly $$$Q$$$ lines with a single integer in each that represent the solution. Output the solutions in the order the queries were asked in.</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> 10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8 </pre></div><div class="output"><div class="title">Output</div><pre> 3 0 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>For the first query we can notice that $$$F(3, 10) = 1,\ F(9, 10) = 1$$$ and $$$F(10, 10) = 1$$$.</p><p>For the second query no $$$x$$$ satisfies condition $$$F(x, 5) = 7$$$.</p><p>For the third query $$$F(5, 10) = 6$$$ holds.</p><p>For the fourth query $$$F(3, 1) = 1.$$$</p><p>For the fifth query no $$$x$$$ satisfies condition $$$F(x, 10) = 8$$$.</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 10:44: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:'8124859d6dfc1646',t:'MTY5NjY2NDY5OC41NDQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\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"]
["\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "*2900"]
1218I
1218
I
ru
I. The Light Square
<div class="problem-statement"><div class="header"><div class="title">I. The Light Square</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an $$$N \times N$$$ lightbulbs square board with a magical lightbulb bar of size $$$N \times 1$$$ that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: </p><p>It can be placed on any row or column </p><p>The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties </p><p>The entire bar needs to be fully placed on a board </p><p>The lights of the magical bar never change </p><p>If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on </p><p>The magical bar can be used an infinite number of times </p><p>Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any. </p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one positive integer number $$$N\ (1 \leq N \leq 2000)$$$ representing the size of the square board. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the initial state of the square board starting from the top row. If the character in a string is 1 it means the light is turned on, otherwise it is off. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the desired state of the square board starting from the top row that was given to Alice by Bob. </p><p>The last line is one string of length $$$N$$$ consisting of 1's and 0's representing the pattern of the magical bar in a left to right order. </p></div><div class="output-specification"><div class="section-title">Output</div><p>Transform the instructions for Alice in order to transform the square board into the pattern Bob gave her. The first line of the output contains an integer number $$$M\ (0 \leq M \leq 10^5$$$) representing the number of times Alice will need to apply the magical bar. </p><p>The next $$$M$$$ lines are of the form "col $$$X$$$" or "row $$$X$$$", where $$$X$$$ is $$$0$$$-based index of the matrix, meaning the magical bar should be applied to either row $$$X$$$ or column $$$X$$$. If there is no solution, print only -1. In case of multiple solutions print any correct one. </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 11 11 00 01 11 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 2 10 00 00 00 10 </pre></div><div class="output"><div class="title">Output</div><pre> 1 row 0 </pre></div><div class="input"><div class="title">Input</div><pre> 3 110 011 100 100 011 100 100 </pre></div><div class="output"><div class="title">Output</div><pre> 3 row 0 col 0 col 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>Example 1: It is impossible to transform square board from one format to another</p><p>Example 2: Magic bar can be applied on first row or column.</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="32998e0082a63667476009fdb2952847"/> <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="d5170437fa0ecd143fc9485538512119c03adfd1"/> <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='32998e0082a63667476009fdb2952847'>&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%2F1218%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='32998e0082a63667476009fdb2952847'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1218">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='32998e0082a63667476009fdb2952847'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1218/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='32998e0082a63667476009fdb2952847'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412341"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='32998e0082a63667476009fdb2952847'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412341"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9338" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div1.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="9339" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9344" resourceName="E" 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/1218">Задачи</a></li> <li><a href="/contest/1218/submit">Отослать</a></li> <li><a href="/contest/1218/my">Мои посылки</a></li> <li><a href="/contest/1218/status">Статус</a></li> <li><a href="/contest/1218/standings">Положение</a></li> <li><a href="/contest/1218/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_092e575c1df8200ee243d135059f264ca70c5a8f"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. The Light Square</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an $$$N \times N$$$ lightbulbs square board with a magical lightbulb bar of size $$$N \times 1$$$ that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: </p><p>It can be placed on any row or column </p><p>The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties </p><p>The entire bar needs to be fully placed on a board </p><p>The lights of the magical bar never change </p><p>If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on </p><p>The magical bar can be used an infinite number of times </p><p>Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any. </p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one positive integer number $$$N\ (1 \leq N \leq 2000)$$$ representing the size of the square board. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the initial state of the square board starting from the top row. If the character in a string is 1 it means the light is turned on, otherwise it is off. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the desired state of the square board starting from the top row that was given to Alice by Bob. </p><p>The last line is one string of length $$$N$$$ consisting of 1's and 0's representing the pattern of the magical bar in a left to right order. </p></div><div class="output-specification"><div class="section-title">Output</div><p>Transform the instructions for Alice in order to transform the square board into the pattern Bob gave her. The first line of the output contains an integer number $$$M\ (0 \leq M \leq 10^5$$$) representing the number of times Alice will need to apply the magical bar. </p><p>The next $$$M$$$ lines are of the form &quot;col $$$X$$$&quot; or &quot;row $$$X$$$&quot;, where $$$X$$$ is $$$0$$$-based index of the matrix, meaning the magical bar should be applied to either row $$$X$$$ or column $$$X$$$. If there is no solution, print only -1. In case of multiple solutions print any correct one. </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 11 11 00 01 11 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 2 10 00 00 00 10 </pre></div><div class="output"><div class="title">Output</div><pre> 1 row 0 </pre></div><div class="input"><div class="title">Input</div><pre> 3 110 011 100 100 011 100 100 </pre></div><div class="output"><div class="title">Output</div><pre> 3 row 0 col 0 col 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>Example 1: It is impossible to transform square board from one format to another</p><p>Example 2: Magic bar can be applied on first row or column.</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 10:44: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:'812485a58aa57b67',t:'MTY5NjY2NDY5OS44ODIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["2-SAT (2-satisfiability)", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\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"]
["2-sat", "\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", "*2100"]
1219A
1219
A
ru
A. BubbleReactor
<div class="problem-statement"><div class="header"><div class="title">A. BubbleReactor</div><div class="time-limit"><div class="property-title">time limit per test</div>1.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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 in charge of the BubbleReactor. It consists of $$$N$$$ BubbleCores connected with $$$N$$$ lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.</p><p>Your task is to start the BubbleReactor by starting each BubbleCore. In order for a BubbleCore to be started it needs to be receiving power from a directly connected BubbleCore which is already started. However, you can kick-start one BubbleCore manually without needing power. It is guaranteed that all BubbleCores can be started.</p><p>Before the BubbleCore boot up procedure its potential is calculated as the number of BubbleCores it can power on (the number of inactive BubbleCores which are connected to it directly or with any number of inactive BubbleCores in between, itself included)</p><p>Start the BubbleReactor so that the sum of all BubbleCores' potentials is maximum.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one integer $$$N (3 \leq N \leq 15.000)$$$, the number of BubbleCores.</p><p>The following N lines contain two integers $$$U, V (0 \leq U \neq V &lt; N)$$$ denoting that there exists electrical wiring between BubbleCores $$$U$$$ and $$$V$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Single integer, the maximum sum of all BubbleCores' potentials.</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> 10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 51 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If we start by kickstarting BubbleCup 8 and then turning on cores 7, 2, 1, 3, 0, 9, 4, 5, 6 in that order we get potentials 10 + 9 + 8 + 7 + 6 + 5 + 1 + 3 + 1 + 1 = 51</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="39d00d3970218127fb2f9d0d1cec13ab"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='39d00d3970218127fb2f9d0d1cec13ab'>&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%2F1219%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='39d00d3970218127fb2f9d0d1cec13ab'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='39d00d3970218127fb2f9d0d1cec13ab'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='39d00d3970218127fb2f9d0d1cec13ab'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412342"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='39d00d3970218127fb2f9d0d1cec13ab'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412342"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_e663ae962ecf6e4dea6401e7eedc64de511e1702"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. BubbleReactor</div><div class="time-limit"><div class="property-title">time limit per test</div>1.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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 in charge of the BubbleReactor. It consists of $$$N$$$ BubbleCores connected with $$$N$$$ lines of electrical wiring. Each electrical wiring connects two distinct BubbleCores. There are no BubbleCores connected with more than one line of electrical wiring.</p><p>Your task is to start the BubbleReactor by starting each BubbleCore. In order for a BubbleCore to be started it needs to be receiving power from a directly connected BubbleCore which is already started. However, you can kick-start one BubbleCore manually without needing power. It is guaranteed that all BubbleCores can be started.</p><p>Before the BubbleCore boot up procedure its potential is calculated as the number of BubbleCores it can power on (the number of inactive BubbleCores which are connected to it directly or with any number of inactive BubbleCores in between, itself included)</p><p>Start the BubbleReactor so that the sum of all BubbleCores' potentials is maximum.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one integer $$$N (3 \leq N \leq 15.000)$$$, the number of BubbleCores.</p><p>The following N lines contain two integers $$$U, V (0 \leq U \neq V &lt; N)$$$ denoting that there exists electrical wiring between BubbleCores $$$U$$$ and $$$V$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Single integer, the maximum sum of all BubbleCores' potentials.</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> 10 0 1 0 3 0 4 0 9 1 2 2 3 2 7 4 5 4 6 7 8 </pre></div><div class="output"><div class="title">Output</div><pre> 51 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If we start by kickstarting BubbleCup 8 and then turning on cores 7, 2, 1, 3, 0, 9, 4, 5, 6 in that order we get potentials 10 + 9 + 8 + 7 + 6 + 5 + 1 + 3 + 1 + 1 = 51</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 10:45: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:'812485addbfa9db0',t:'MTY5NjY2NDcwMS4zMDEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1219B
1219
B
ru
B. Xor Spanning Tree
<div class="problem-statement"><div class="header"><div class="title">B. Xor Spanning Tree</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of $$$N$$$ planets. Between them, there are $$$M$$$ bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached using these wormholes. It is also guaranteed that no wormhole connects planet to itself and that no two different wormholes connect same pair of planets. </p><p>We call a path that begins at one planet, visits other planets and each of them at most once and returns to starting point a <span class="tex-font-style-it">tour</span>. Interplanetary Safety Regulations guarantee that each planet belongs to at most one <span class="tex-font-style-it">tour</span> and that there are at most $$$42$$$ <span class="tex-font-style-it">tours</span>.</p><p>After many eons of usage, wormholes need to be repaired and each wormhole has the cost $$$W_{i}$$$ which needs to be payed for reparation. Unfortunately, the Senate of Bubbleland is short on budget. Therefore, they have decided only to fix as many wormholes as they need in order to have all planets reachable from capital and to pay as little money as they have to for this repair. However the way in which the Senate calculates the cost is different. Cost of the set of reparations is binary xor of costs of each individual reparation, that is if reparations to be made have costs $$$A_{1},A_{2},...,A_{k}$$$, the cost of entire set is $$$A_{1} \oplus A_{2} \oplus ... \oplus A_{k}$$$.</p><p>Now the Senate would like to know how much money do they have to pay and also the number of different ways to achieve that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line of input contains two numbers $$$N (1 \leq N \leq 100.000)$$$, the number of planets and $$$M (1 \leq M \leq 100.041)$$$, the number of wormholes. Following $$$M$$$ lines contain three numbers $$$U, V (1 \leq U \neq V \leq N)$$$ and $$$W (1 \leq W \leq 100.000)$$$, meaning that there exists a wormhole connecting planets $$$U$$$ and $$$V$$$, with repair cost of $$$W$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output two numbers, the smallest possible cost of entire reparation and the number of different valid reparations with that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</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 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>We can repair wormholes $$$1$$$,$$$2$$$,$$$3$$$,$$$5$$$ and $$$6$$$, paying $$$5 \oplus 1\oplus 2 \oplus 3 \oplus 4=1$$$, one can check that this is the cheapest repair in which all of the planets are connected and the only valid repair with that cost.</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="b62654b0f77414e7957c3abecc8353ac"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='b62654b0f77414e7957c3abecc8353ac'>&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%2F1219%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='b62654b0f77414e7957c3abecc8353ac'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='b62654b0f77414e7957c3abecc8353ac'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b62654b0f77414e7957c3abecc8353ac'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412343"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b62654b0f77414e7957c3abecc8353ac'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412343"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_d6de2d2b0058ffeea134c9df73c4265163f191ba"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Xor Spanning Tree</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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>In the galaxy far far away is the ancient interplanetary republic of Bubbleland, consisting of $$$N$$$ planets. Between them, there are $$$M$$$ bidirectional wormholes, each connecting a pair of planets. Bubbleland is a very centralized republic, having a capital planet Whiteplanet, from which any another planet can be reached using these wormholes. It is also guaranteed that no wormhole connects planet to itself and that no two different wormholes connect same pair of planets. </p><p>We call a path that begins at one planet, visits other planets and each of them at most once and returns to starting point a <span class="tex-font-style-it">tour</span>. Interplanetary Safety Regulations guarantee that each planet belongs to at most one <span class="tex-font-style-it">tour</span> and that there are at most $$$42$$$ <span class="tex-font-style-it">tours</span>.</p><p>After many eons of usage, wormholes need to be repaired and each wormhole has the cost $$$W_{i}$$$ which needs to be payed for reparation. Unfortunately, the Senate of Bubbleland is short on budget. Therefore, they have decided only to fix as many wormholes as they need in order to have all planets reachable from capital and to pay as little money as they have to for this repair. However the way in which the Senate calculates the cost is different. Cost of the set of reparations is binary xor of costs of each individual reparation, that is if reparations to be made have costs $$$A_{1},A_{2},...,A_{k}$$$, the cost of entire set is $$$A_{1} \oplus A_{2} \oplus ... \oplus A_{k}$$$.</p><p>Now the Senate would like to know how much money do they have to pay and also the number of different ways to achieve that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line of input contains two numbers $$$N (1 \leq N \leq 100.000)$$$, the number of planets and $$$M (1 \leq M \leq 100.041)$$$, the number of wormholes. Following $$$M$$$ lines contain three numbers $$$U, V (1 \leq U \neq V \leq N)$$$ and $$$W (1 \leq W \leq 100.000)$$$, meaning that there exists a wormhole connecting planets $$$U$$$ and $$$V$$$, with repair cost of $$$W$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output two numbers, the smallest possible cost of entire reparation and the number of different valid reparations with that cost <span class="tex-font-style-bf">modulo $$$1000000007$$$</span>.</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 6 4 1 5 5 2 1 6 3 2 1 2 6 1 3 3 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 1 1</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>We can repair wormholes $$$1$$$,$$$2$$$,$$$3$$$,$$$5$$$ and $$$6$$$, paying $$$5 \oplus 1\oplus 2 \oplus 3 \oplus 4=1$$$, one can check that this is the cheapest repair in which all of the planets are connected and the only valid repair with that cost.</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 10:45: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:'812485b6dec09d9e',t:'MTY5NjY2NDcwMi42MTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
["*2400"]
1219C
1219
C
ru
C. Periodic integer number
<div class="problem-statement"><div class="header"><div class="title">C. Periodic integer number</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alice became interested in periods of integer numbers. We say positive $$$X$$$ integer number is periodic with length $$$L$$$ if there exists positive integer number $$$P$$$ with $$$L$$$ digits such that $$$X$$$ can be written as $$$PPPP…P$$$. For example:</p><p>$$$X = 123123123$$$ is periodic number with length $$$L = 3$$$ and $$$L = 9$$$</p><p>$$$X = 42424242$$$ is periodic number with length $$$L = 2,L = 4$$$ and $$$L = 8$$$</p><p>$$$X = 12345$$$ is periodic number with length $$$L = 5$$$</p><p>For given positive period length $$$L$$$ and positive integer number $$$A$$$, Alice wants to find smallest integer number $$$X$$$ strictly greater than $$$A$$$ that is periodic with length L.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one positive integer number $$$L \ (1 \leq L \leq 10^5)$$$ representing length of the period. Second line contains one positive integer number $$$A \ (1 \leq A \leq 10^{100 000})$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One positive integer number representing smallest positive number that is periodic with length $$$L$$$ and is greater than $$$A$$$.</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 123456 </pre></div><div class="output"><div class="title">Output</div><pre> 124124 </pre></div><div class="input"><div class="title">Input</div><pre> 3 12345 </pre></div><div class="output"><div class="title">Output</div><pre> 100100 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).</p><p>In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)</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="dbe8ca95cb8d9a9ef985e7d9b6b6c53e"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='dbe8ca95cb8d9a9ef985e7d9b6b6c53e'>&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%2F1219%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='dbe8ca95cb8d9a9ef985e7d9b6b6c53e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='dbe8ca95cb8d9a9ef985e7d9b6b6c53e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='dbe8ca95cb8d9a9ef985e7d9b6b6c53e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412344"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='dbe8ca95cb8d9a9ef985e7d9b6b6c53e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412344"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_6d1844bbfaca58ada8d31e1a85acd054bbe0b583"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Periodic integer number</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alice became interested in periods of integer numbers. We say positive $$$X$$$ integer number is periodic with length $$$L$$$ if there exists positive integer number $$$P$$$ with $$$L$$$ digits such that $$$X$$$ can be written as $$$PPPP…P$$$. For example:</p><p>$$$X = 123123123$$$ is periodic number with length $$$L = 3$$$ and $$$L = 9$$$</p><p>$$$X = 42424242$$$ is periodic number with length $$$L = 2,L = 4$$$ and $$$L = 8$$$</p><p>$$$X = 12345$$$ is periodic number with length $$$L = 5$$$</p><p>For given positive period length $$$L$$$ and positive integer number $$$A$$$, Alice wants to find smallest integer number $$$X$$$ strictly greater than $$$A$$$ that is periodic with length L.</p></div><div class="input-specification"><div class="section-title">Input</div><p>First line contains one positive integer number $$$L \ (1 \leq L \leq 10^5)$$$ representing length of the period. Second line contains one positive integer number $$$A \ (1 \leq A \leq 10^{100 000})$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One positive integer number representing smallest positive number that is periodic with length $$$L$$$ and is greater than $$$A$$$.</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 123456 </pre></div><div class="output"><div class="title">Output</div><pre> 124124 </pre></div><div class="input"><div class="title">Input</div><pre> 3 12345 </pre></div><div class="output"><div class="title">Output</div><pre> 100100 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In first example 124124 is the smallest number greater than 123456 that can be written with period L = 3 (P = 124).</p><p>In the second example 100100 is the smallest number greater than 12345 with period L = 3 (P=100)</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 10:45: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:'812485bf1d149d58',t:'MTY5NjY2NDcwMy45NjYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0420\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f, \u0442\u0435\u0445\u043d\u0438\u043a\u0430 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u044f, \u0441\u0438\u043c\u0443\u043b\u044f\u0446\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1700"]
1219D
1219
D
ru
D. Workout plan
<div class="problem-statement"><div class="header"><div class="title">D. Workout plan</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $$$X[i]$$$ grams on day $$$i$$$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $$$A$$$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $$$C[i]$$$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $$$K$$$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first one contains two integer numbers, integers $$$N$$$ $$$(1 \leq N \leq 10^5)$$$ and $$$K$$$ $$$(1 \leq K \leq 10^5)$$$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $$$N$$$ integer numbers $$$X[i]$$$ $$$(1 \leq X[i] \leq 10^9)$$$ separated by a single space representing how many grams Alan wants to lift on day $$$i$$$. The third line contains one integer number $$$A$$$ $$$(1 \leq A \leq 10^9)$$$ representing permanent performance gains from a single drink. The last line contains $$$N$$$ integer numbers $$$C[i]$$$ $$$(1 \leq C[i] \leq 10^9)$$$ , representing cost of performance booster drink in the gym he visits on day $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -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> 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> 5 </pre></div><div class="input"><div class="title">Input</div><pre> 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 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="76370805a32802499a5a607033679b07"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='76370805a32802499a5a607033679b07'>&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%2F1219%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='76370805a32802499a5a607033679b07'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='76370805a32802499a5a607033679b07'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='76370805a32802499a5a607033679b07'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412345"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='76370805a32802499a5a607033679b07'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412345"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_2686815c09ca99ca0483b59ec900c61916980727"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Workout plan</div><div class="time-limit"><div class="property-title">time limit per test</div>1 second</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $$$X[i]$$$ grams on day $$$i$$$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $$$A$$$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $$$C[i]$$$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $$$K$$$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $$$-1$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first one contains two integer numbers, integers $$$N$$$ $$$(1 \leq N \leq 10^5)$$$ and $$$K$$$ $$$(1 \leq K \leq 10^5)$$$ – representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $$$N$$$ integer numbers $$$X[i]$$$ $$$(1 \leq X[i] \leq 10^9)$$$ separated by a single space representing how many grams Alan wants to lift on day $$$i$$$. The third line contains one integer number $$$A$$$ $$$(1 \leq A \leq 10^9)$$$ representing permanent performance gains from a single drink. The last line contains $$$N$$$ integer numbers $$$C[i]$$$ $$$(1 \leq C[i] \leq 10^9)$$$ , representing cost of performance booster drink in the gym he visits on day $$$i$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -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> 5 10000 10000 30000 30000 40000 20000 20000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> 5 </pre></div><div class="input"><div class="title">Input</div><pre> 5 10000 10000 40000 30000 30000 20000 10000 5 2 8 3 6 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>First example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=D]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:45: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:'812485c77fc975b7',t:'MTY5NjY2NDcwNS4yNjIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*1500"]
1219E
1219
E
ru
E. Jumping Transformers
<div class="problem-statement"><div class="header"><div class="title">E. Jumping Transformers</div><div class="time-limit"><div class="property-title">time limit per test</div>4 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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, the mighty Blackout, are standing in the upper-left $$$(0,0)$$$ corner of $$$N$$$x$$$M$$$ matrix. You must move either right or down each second. </p><p>There are $$$K$$$ transformers jumping around the matrix in the following way. Each transformer starts jumping from position $$$(x,y)$$$, at time $$$t$$$, and jumps to the next position each second. The $$$x$$$-axes grows downwards, and $$$y$$$-axes grows to the right. The order of jumping positions is defined as $$${(x,y),(x+d,y-d),(x+d,y),(x,y+d)}$$$, and is periodic. Before time $$$t$$$ transformer is not in the matrix.</p><p>You want to arrive to the bottom-right corner $$$(N-1,M-1)$$$, while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.</p><p>After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first line, integers $$$N$$$,$$$M$$$ ($$$1 \leq N, M \leq 500$$$), representing size of the matrix, and $$$K$$$ ($$$0 \leq K \leq 5*10^5$$$) , the number of jumping transformers.</p><p>In next $$$K$$$ lines, for each transformer, numbers $$$x$$$, $$$y$$$, $$$d$$$ ($$$d \geq 1$$$), $$$t$$$ ($$$0 \leq t \leq N+M-2$$$), and $$$e$$$ ($$$0 \leq e \leq 10^9$$$), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.</p><p>It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.</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 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 </pre></div><div class="output"><div class="title">Output</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.</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="c92820f26fa39adc762ea13e766e7b13"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='c92820f26fa39adc762ea13e766e7b13'>&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%2F1219%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='c92820f26fa39adc762ea13e766e7b13'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='c92820f26fa39adc762ea13e766e7b13'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='c92820f26fa39adc762ea13e766e7b13'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412346"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c92820f26fa39adc762ea13e766e7b13'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412346"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_cdd7e2a1ca4ec9a1c9c31d36b7dbbc7f11c2ca7a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Jumping Transformers</div><div class="time-limit"><div class="property-title">time limit per test</div>4 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>128 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, the mighty Blackout, are standing in the upper-left $$$(0,0)$$$ corner of $$$N$$$x$$$M$$$ matrix. You must move either right or down each second. </p><p>There are $$$K$$$ transformers jumping around the matrix in the following way. Each transformer starts jumping from position $$$(x,y)$$$, at time $$$t$$$, and jumps to the next position each second. The $$$x$$$-axes grows downwards, and $$$y$$$-axes grows to the right. The order of jumping positions is defined as $$${(x,y),(x+d,y-d),(x+d,y),(x,y+d)}$$$, and is periodic. Before time $$$t$$$ transformer is not in the matrix.</p><p>You want to arrive to the bottom-right corner $$$(N-1,M-1)$$$, while slaying transformers and losing the least possible amount of energy. When you meet the transformer (or more of them) in the matrix field, you must kill them all, and you lose the sum of the energy amounts required to kill each transformer.</p><p>After the transformer is killed, he of course stops jumping, falls into the abyss and leaves the matrix world. Output minimum possible amount of energy wasted.</p></div><div class="input-specification"><div class="section-title">Input</div><p>In the first line, integers $$$N$$$,$$$M$$$ ($$$1 \leq N, M \leq 500$$$), representing size of the matrix, and $$$K$$$ ($$$0 \leq K \leq 5*10^5$$$) , the number of jumping transformers.</p><p>In next $$$K$$$ lines, for each transformer, numbers $$$x$$$, $$$y$$$, $$$d$$$ ($$$d \geq 1$$$), $$$t$$$ ($$$0 \leq t \leq N+M-2$$$), and $$$e$$$ ($$$0 \leq e \leq 10^9$$$), representing starting coordinates of transformer, jumping positions distance in pattern described above, time when transformer starts jumping, and energy required to kill it.</p><p>It is guaranteed that all 4 of jumping points of the transformers are within matrix coordinates</p></div><div class="output-specification"><div class="section-title">Output</div><p>Print single integer, the minimum possible amount of energy wasted, for Blackout to arrive at bottom-right corner.</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 3 5 0 1 1 0 7 1 1 1 0 10 1 1 1 1 2 1 1 1 2 2 0 1 1 2 3 </pre></div><div class="output"><div class="title">Output</div><pre> 9</pre></div></div></div><div class="note"><div class="section-title">Note</div><p>If Blackout takes the path from (0, 0) to (2, 0), and then from (2, 0) to (2, 2) he will need to kill the first and third transformer for a total energy cost of 9. There exists no path with less energy value.</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 10:45: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:'812485cf9fbf1683',t:'MTY5NjY2NDcwNi41NTIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
1219G
1219
G
ru
G. Harvester
<div class="problem-statement"><div class="header"><div class="title">G. Harvester</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>It is Bubble Cup finals season and farmer Johnny Bubbles must harvest his bubbles. The bubbles are in a rectangular bubblefield formed of $$$N$$$ x $$$M$$$ square parcels divided into $$$N$$$ rows and $$$M$$$ columns. The parcel in $$$i^{th}$$$ row and $$$j^{th}$$$ column yields $$$A_{i,j}$$$ bubbles.</p><p>Johnny Bubbles has available a very special self-driving bubble harvester that, once manually positioned at the beginning of a row or column, automatically harvests all the bubbles in that row or column. Once the harvester reaches the end of the row or column it stops and must be repositioned. The harvester can pass through any parcel any number of times, but it can collect bubbles from the parcel only once.</p><p>Johnny is very busy farmer, so he is available to manually position the harvester at most four times per day. Johnny is also impatient, so he wants to harvest as many bubbles as possible on the first day.</p><p>Please help Johnny to calculate what is the maximum number of bubbles he can collect on the first day.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1$$$ $$$\leq$$$ $$$N$$$, $$$M$$$ $$$\leq$$$ $$$N$$$ * $$$M$$$ $$$\leq$$$ $$$10^{5}$$$) - the bubblefield size.</p><p>Each of the next $$$N$$$ lines contains $$$M$$$ integers. The $$$j^{th}$$$ element in the $$$i^{th}$$$ line is $$$A_{i,j}$$$ ($$$0$$$ $$$\leq$$$ $$$a_{i,j}$$$ $$$\leq$$$ $$$10^{9}$$$) — the yield of the parcel located in the $$$i^{th}$$$ row and the $$$j^{th}$$$ column.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output contains one integer number - maximum number of the bubbles Johnny can harvest on the first day.</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 1 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 10 </pre></div><div class="input"><div class="title">Input</div><pre> 5 5 0 9 2 7 0 9 0 3 0 5 0 8 0 3 1 6 7 4 3 9 3 6 4 1 0 </pre></div><div class="output"><div class="title">Output</div><pre> 80 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, farmer Johnny can harvest all the bubbles by positioning the harvester on the first and the second row.</p><p>In the second example, one way Johnny can harvest maximum number of bubbles is to position the harvester in the second row, the fourth row, the second column and the fourth column.</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="c918fd436ba646503daa94e82cf713ba"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='c918fd436ba646503daa94e82cf713ba'>&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%2F1219%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='c918fd436ba646503daa94e82cf713ba'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='c918fd436ba646503daa94e82cf713ba'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='c918fd436ba646503daa94e82cf713ba'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412348"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c918fd436ba646503daa94e82cf713ba'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412348"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_683959c8c475213d5d18f2200bea1ddd61fdd8c5"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Harvester</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>It is Bubble Cup finals season and farmer Johnny Bubbles must harvest his bubbles. The bubbles are in a rectangular bubblefield formed of $$$N$$$ x $$$M$$$ square parcels divided into $$$N$$$ rows and $$$M$$$ columns. The parcel in $$$i^{th}$$$ row and $$$j^{th}$$$ column yields $$$A_{i,j}$$$ bubbles.</p><p>Johnny Bubbles has available a very special self-driving bubble harvester that, once manually positioned at the beginning of a row or column, automatically harvests all the bubbles in that row or column. Once the harvester reaches the end of the row or column it stops and must be repositioned. The harvester can pass through any parcel any number of times, but it can collect bubbles from the parcel only once.</p><p>Johnny is very busy farmer, so he is available to manually position the harvester at most four times per day. Johnny is also impatient, so he wants to harvest as many bubbles as possible on the first day.</p><p>Please help Johnny to calculate what is the maximum number of bubbles he can collect on the first day.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains two integers $$$N$$$ and $$$M$$$ ($$$1$$$ $$$\leq$$$ $$$N$$$, $$$M$$$ $$$\leq$$$ $$$N$$$ * $$$M$$$ $$$\leq$$$ $$$10^{5}$$$) - the bubblefield size.</p><p>Each of the next $$$N$$$ lines contains $$$M$$$ integers. The $$$j^{th}$$$ element in the $$$i^{th}$$$ line is $$$A_{i,j}$$$ ($$$0$$$ $$$\leq$$$ $$$a_{i,j}$$$ $$$\leq$$$ $$$10^{9}$$$) — the yield of the parcel located in the $$$i^{th}$$$ row and the $$$j^{th}$$$ column.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output contains one integer number - maximum number of the bubbles Johnny can harvest on the first day.</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 1 2 3 4 </pre></div><div class="output"><div class="title">Output</div><pre> 10 </pre></div><div class="input"><div class="title">Input</div><pre> 5 5 0 9 2 7 0 9 0 3 0 5 0 8 0 3 1 6 7 4 3 9 3 6 4 1 0 </pre></div><div class="output"><div class="title">Output</div><pre> 80 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>In the first example, farmer Johnny can harvest all the bubbles by positioning the harvester on the first and the second row.</p><p>In the second example, one way Johnny can harvest maximum number of bubbles is to position the harvester in the second row, the fourth row, the second column and the fourth column.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=G]"); let uuid = $problem.attr("data-uuid"); let statementText = convertStatementToText($problem.find(".ttypography").get(0)); let previousStatementText = Codeforces.getFromStorage(uuid); if (previousStatementText) { if (previousStatementText !== statementText) { $problem.find(".diff-notifier").show(); $problem.find(".diff-notifier-close").click(function() { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); $problem.find(".diff-notifier").hide(); }); $problem.find("a.view-changes").click(function() { $.post("/data/diff", {action: "getDiff", a: previousStatementText, b: statementText}, function (result) { if (result["success"] === "true") { Codeforces.facebox(".diff-popup", "//codeforces.org/s/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 10:45: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:'812485d7aa3b0c36',t:'MTY5NjY2NDcwNy44NTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2000"]
1219H
1219
H
ru
H. Function Composition
<div class="problem-statement"><div class="header"><div class="title">H. Function Composition</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.</p><p>First, let us define several things. We define function $$$F$$$ on the array $$$A$$$ such that $$$F(i, 1) = A[i]$$$ and $$$F(i, m) = A[F(i, m - 1)]$$$ for $$$m &gt; 1$$$. In other words, value $$$F(i, m)$$$ represents composition $$$A[...A[i]]$$$ applied $$$m$$$ times.</p><p>You are given an array of length $$$N$$$ with non-negative integers. You are expected to give an answer on $$$Q$$$ queries. Each query consists of two numbers – $$$m$$$ and $$$y$$$. For each query determine how many $$$x$$$ exist such that $$$F(x,m) = y$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ $$$(1 \leq N \leq 2 \cdot 10^5)$$$ – the size of the array $$$A$$$. The next line contains $$$N$$$ non-negative integers – the array $$$A$$$ itself $$$(1 \leq A_i \leq N)$$$. The next line contains one integer $$$Q$$$ $$$(1 \leq Q \leq 10^5)$$$ – the number of queries. Each of the next $$$Q$$$ lines contain two integers $$$m$$$ and $$$y$$$ $$$(1 \leq m \leq 10^{18}, 1\leq y \leq N)$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output exactly $$$Q$$$ lines with a single integer in each that represent the solution. Output the solutions in the order the queries were asked in.</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> 10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8 </pre></div><div class="output"><div class="title">Output</div><pre> 3 0 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>For the first query we can notice that $$$F(3, 10) = 1,\ F(9, 10) = 1$$$ and $$$F(10, 10) = 1$$$.</p><p>For the second query no $$$x$$$ satisfies condition $$$F(x, 5) = 7$$$.</p><p>For the third query $$$F(5, 10) = 6$$$ holds.</p><p>For the fourth query $$$F(3, 1) = 1.$$$</p><p>For the fifth query no $$$x$$$ satisfies condition $$$F(x, 10) = 8$$$.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="16288c97a240a28139ff16b4d35bd6e1"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='16288c97a240a28139ff16b4d35bd6e1'>&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%2F1219%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='16288c97a240a28139ff16b4d35bd6e1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='16288c97a240a28139ff16b4d35bd6e1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='16288c97a240a28139ff16b4d35bd6e1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412349"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='16288c97a240a28139ff16b4d35bd6e1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412349"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_a7c191b8974d99dbfe2e364c4a5fc3024df00018"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Function Composition</div><div class="time-limit"><div class="property-title">time limit per test</div>0.5 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>We are definitely not going to bother you with another generic story when Alice finds about an array or when Alice and Bob play some stupid game. This time you'll get a simple, plain text.</p><p>First, let us define several things. We define function $$$F$$$ on the array $$$A$$$ such that $$$F(i, 1) = A[i]$$$ and $$$F(i, m) = A[F(i, m - 1)]$$$ for $$$m &gt; 1$$$. In other words, value $$$F(i, m)$$$ represents composition $$$A[...A[i]]$$$ applied $$$m$$$ times.</p><p>You are given an array of length $$$N$$$ with non-negative integers. You are expected to give an answer on $$$Q$$$ queries. Each query consists of two numbers – $$$m$$$ and $$$y$$$. For each query determine how many $$$x$$$ exist such that $$$F(x,m) = y$$$.</p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one integer $$$N$$$ $$$(1 \leq N \leq 2 \cdot 10^5)$$$ – the size of the array $$$A$$$. The next line contains $$$N$$$ non-negative integers – the array $$$A$$$ itself $$$(1 \leq A_i \leq N)$$$. The next line contains one integer $$$Q$$$ $$$(1 \leq Q \leq 10^5)$$$ – the number of queries. Each of the next $$$Q$$$ lines contain two integers $$$m$$$ and $$$y$$$ $$$(1 \leq m \leq 10^{18}, 1\leq y \leq N)$$$.</p></div><div class="output-specification"><div class="section-title">Output</div><p>Output exactly $$$Q$$$ lines with a single integer in each that represent the solution. Output the solutions in the order the queries were asked in.</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> 10 2 3 1 5 6 4 2 10 7 7 5 10 1 5 7 10 6 1 1 10 8 </pre></div><div class="output"><div class="title">Output</div><pre> 3 0 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>For the first query we can notice that $$$F(3, 10) = 1,\ F(9, 10) = 1$$$ and $$$F(10, 10) = 1$$$.</p><p>For the second query no $$$x$$$ satisfies condition $$$F(x, 5) = 7$$$.</p><p>For the third query $$$F(5, 10) = 6$$$ holds.</p><p>For the fourth query $$$F(3, 1) = 1.$$$</p><p>For the fifth query no $$$x$$$ satisfies condition $$$F(x, 10) = 8$$$.</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 10:45: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:'812485dfc8df9d9e',t:'MTY5NjY2NDcwOS4xMzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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"]
["*2900"]
1219I
1219
I
ru
I. The Light Square
<div class="problem-statement"><div class="header"><div class="title">I. The Light Square</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an $$$N \times N$$$ lightbulbs square board with a magical lightbulb bar of size $$$N \times 1$$$ that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: </p><p>It can be placed on any row or column </p><p>The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties </p><p>The entire bar needs to be fully placed on a board </p><p>The lights of the magical bar never change </p><p>If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on </p><p>The magical bar can be used an infinite number of times </p><p>Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any. </p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one positive integer number $$$N\ (1 \leq N \leq 2000)$$$ representing the size of the square board. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the initial state of the square board starting from the top row. If the character in a string is 1 it means the light is turned on, otherwise it is off. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the desired state of the square board starting from the top row that was given to Alice by Bob. </p><p>The last line is one string of length $$$N$$$ consisting of 1's and 0's representing the pattern of the magical bar in a left to right order. </p></div><div class="output-specification"><div class="section-title">Output</div><p>Transform the instructions for Alice in order to transform the square board into the pattern Bob gave her. The first line of the output contains an integer number $$$M\ (0 \leq M \leq 10^5$$$) representing the number of times Alice will need to apply the magical bar. </p><p>The next $$$M$$$ lines are of the form "col $$$X$$$" or "row $$$X$$$", where $$$X$$$ is $$$0$$$-based index of the matrix, meaning the magical bar should be applied to either row $$$X$$$ or column $$$X$$$. If there is no solution, print only -1. In case of multiple solutions print any correct one. </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 11 11 00 01 11 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 2 10 00 00 00 10 </pre></div><div class="output"><div class="title">Output</div><pre> 1 row 0 </pre></div><div class="input"><div class="title">Input</div><pre> 3 110 011 100 100 011 100 100 </pre></div><div class="output"><div class="title">Output</div><pre> 3 row 0 col 0 col 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>Example 1: It is impossible to transform square board from one format to another</p><p>Example 2: Magic bar can be applied on first row or column.</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="2fcf7452f422e1635a5a1ca1d3f5f9ee"/> <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="2c5967cf0cd307b5b7996583f17436e3db2c3562"/> <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='2fcf7452f422e1635a5a1ca1d3f5f9ee'>&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%2F1219%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='2fcf7452f422e1635a5a1ca1d3f5f9ee'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1219">Bubble Cup 12 - Finals [Online Mirror, unrated, 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='2fcf7452f422e1635a5a1ca1d3f5f9ee'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1219/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='2fcf7452f422e1635a5a1ca1d3f5f9ee'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="412350"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='2fcf7452f422e1635a5a1ca1d3f5f9ee'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="412350"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69752" title="Mirror of Bubble Cup 12 Finals on Codeforces" target="_blank">Анонс <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9337" resourceName="Mirror of Bubble Cup 12 Finals on Codeforces" 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="https://assets.codeforces.com/files/b12/div2.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="9340" 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="https://www.bubblecup.org/Content/Media/Booklet2019.pdf" title="E" target="_blank">E <span class="resource-locale">(англ.)</span></a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9345" resourceName="E" 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/1219">Задачи</a></li> <li><a href="/contest/1219/submit">Отослать</a></li> <li><a href="/contest/1219/my">Мои посылки</a></li> <li><a href="/contest/1219/status">Статус</a></li> <li><a href="/contest/1219/standings">Положение</a></li> <li><a href="/contest/1219/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_bb25f0403c46028ca339d0c8a473b6c0bf837a01"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. The Light Square</div><div class="time-limit"><div class="property-title">time limit per test</div>2 seconds</div><div class="memory-limit"><div class="property-title">memory limit per test</div>256 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>For her birthday Alice received an interesting gift from her friends – The Light Square. The Light Square game is played on an $$$N \times N$$$ lightbulbs square board with a magical lightbulb bar of size $$$N \times 1$$$ that has magical properties. At the start of the game some lights on the square board and magical bar are turned on. The goal of the game is to transform the starting light square board pattern into some other pattern using the magical bar without rotating the square board. The magical bar works as follows: </p><p>It can be placed on any row or column </p><p>The orientation of the magical lightbulb must be left to right or top to bottom for it to keep its magical properties </p><p>The entire bar needs to be fully placed on a board </p><p>The lights of the magical bar never change </p><p>If the light on the magical bar is the same as the light of the square it is placed on it will switch the light on the square board off, otherwise it will switch the light on </p><p>The magical bar can be used an infinite number of times </p><p>Alice has a hard time transforming her square board into the pattern Bob gave her. Can you help her transform the board or let her know it is impossible? If there are multiple solutions print any. </p></div><div class="input-specification"><div class="section-title">Input</div><p>The first line contains one positive integer number $$$N\ (1 \leq N \leq 2000)$$$ representing the size of the square board. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the initial state of the square board starting from the top row. If the character in a string is 1 it means the light is turned on, otherwise it is off. </p><p>The next $$$N$$$ lines are strings of length $$$N$$$ consisting of 1's and 0's representing the desired state of the square board starting from the top row that was given to Alice by Bob. </p><p>The last line is one string of length $$$N$$$ consisting of 1's and 0's representing the pattern of the magical bar in a left to right order. </p></div><div class="output-specification"><div class="section-title">Output</div><p>Transform the instructions for Alice in order to transform the square board into the pattern Bob gave her. The first line of the output contains an integer number $$$M\ (0 \leq M \leq 10^5$$$) representing the number of times Alice will need to apply the magical bar. </p><p>The next $$$M$$$ lines are of the form &quot;col $$$X$$$&quot; or &quot;row $$$X$$$&quot;, where $$$X$$$ is $$$0$$$-based index of the matrix, meaning the magical bar should be applied to either row $$$X$$$ or column $$$X$$$. If there is no solution, print only -1. In case of multiple solutions print any correct one. </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 11 11 00 01 11 </pre></div><div class="output"><div class="title">Output</div><pre> -1 </pre></div><div class="input"><div class="title">Input</div><pre> 2 10 00 00 00 10 </pre></div><div class="output"><div class="title">Output</div><pre> 1 row 0 </pre></div><div class="input"><div class="title">Input</div><pre> 3 110 011 100 100 011 100 100 </pre></div><div class="output"><div class="title">Output</div><pre> 3 row 0 col 0 col 1 </pre></div></div></div><div class="note"><div class="section-title">Note</div><p>Example 1: It is impossible to transform square board from one format to another</p><p>Example 2: Magic bar can be applied on first row or column.</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 10:45: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:'812485e7ba957b2f',t:'MTY5NjY2NDcxMC40MTMwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["2-SAT (2-satisfiability)", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["2-sat", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "*2100"]
1220A
1220
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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — длина строки. Вторая строка содержит строку из строчных латинских букв: «z», «e», «r», «o» и «n». </p><p>Гарантируется, что буквы можно переупорядочить таким образом, чтобы они образовывали последовательность слов, каждое из которых является либо словом «zero», что соответствует цифре $$$0$$$, либо словом «one», что соответствует цифре $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможное число в двоичной системе счисления. Выводите двоичные цифры, разделяя их пробелами. Лидирующие нули допустимы.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 ezor </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 nznooeeoer </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере правильная последовательность букв — это «zero».</p><p>Во втором примере правильная последовательность букв — это «oneonezero».</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="710d865745996895011157f14cb1df42"/> <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="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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='710d865745996895011157f14cb1df42'>&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%2F1220%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='710d865745996895011157f14cb1df42'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='710d865745996895011157f14cb1df42'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='710d865745996895011157f14cb1df42'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415028"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='710d865745996895011157f14cb1df42'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415028"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" 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/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" 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/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_349e1c7bf4ba1be052da53c8cc371bac426660b0"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — длина строки. Вторая строка содержит строку из строчных латинских букв: «z», «e», «r», «o» и «n». </p><p>Гарантируется, что буквы можно переупорядочить таким образом, чтобы они образовывали последовательность слов, каждое из которых является либо словом «zero», что соответствует цифре $$$0$$$, либо словом «one», что соответствует цифре $$$1$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите максимально возможное число в двоичной системе счисления. Выводите двоичные цифры, разделяя их пробелами. Лидирующие нули допустимы.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 ezor </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 nznooeeoer </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере правильная последовательность букв — это «zero».</p><p>Во втором примере правильная последовательность букв — это «oneonezero».</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 10:45: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:'812485efbf3d16b7',t:'MTY5NjY2NDcxNC45NzgwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0440\u0435\u0430\u043b\u0438\u0437\u0430\u0446\u0438\u044f", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u043e\u043a\u0438", "*800"]
1220B
1220
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>Саша подросла и пошла в первый класс. В честь этого события мама подарила ей таблицу умножения $$$M$$$ с $$$n$$$ строками и $$$n$$$ столбцами, такую что $$$M_{ij}=a_i \cdot a_j$$$, где $$$a_1, \dots, a_n$$$ — некоторый массив целых положительных чисел.</p><p>Конечно же, девочка решила взять её с собой в школу. Но пока она обедала, хулиган Гриша стёр числа на главной диагонали и выкинул массив $$$a_1, \dots, a_n$$$. Помогите Саше восстановить исходный массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$) —размер таблицы умножения. </p><p>Каждая из следующих $$$n$$$ строк содержит $$$n$$$ целых чисел. $$$j$$$-е число в $$$i$$$-й строке содержит число $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). На главной диагонали таблицы указаны нули, то есть, $$$M_{ii}=0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел, исходный массив $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). Гарантируется, что ответ всегда существует. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9999 10000 9998 </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="6605fed497d55012c357cf965478e1ff"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='6605fed497d55012c357cf965478e1ff'>&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/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=%2Fcontest%2F1220%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='6605fed497d55012c357cf965478e1ff'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='6605fed497d55012c357cf965478e1ff'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='6605fed497d55012c357cf965478e1ff'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415029"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='6605fed497d55012c357cf965478e1ff'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415029"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_121dafee4dfebfa1f1fbbe251aedf63a20702f88"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Саша подросла и пошла в первый класс. В честь этого события мама подарила ей таблицу умножения $$$M$$$ с $$$n$$$ строками и $$$n$$$ столбцами, такую что $$$M_{ij}=a_i \cdot a_j$$$, где $$$a_1, \dots, a_n$$$ — некоторый массив целых положительных чисел.</p><p>Конечно же, девочка решила взять её с собой в школу. Но пока она обедала, хулиган Гриша стёр числа на главной диагонали и выкинул массив $$$a_1, \dots, a_n$$$. Помогите Саше восстановить исходный массив!</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит одно целое число $$$n$$$ ($$$3 \leqslant n \leqslant 10^3$$$) —размер таблицы умножения. </p><p>Каждая из следующих $$$n$$$ строк содержит $$$n$$$ целых чисел. $$$j$$$-е число в $$$i$$$-й строке содержит число $$$M_{ij}$$$ ($$$1 \leq M_{ij} \leq 10^9$$$). На главной диагонали таблицы указаны нули, то есть, $$$M_{ii}=0$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В единственной строке выведите $$$n$$$ целых чисел, исходный массив $$$a_1, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^9$$$). Гарантируется, что ответ всегда существует. Если существует несколько решений, выведите любое из них.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 0 4 6 2 4 4 0 6 2 4 6 6 0 3 6 2 2 3 0 2 4 4 6 2 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 2 3 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 3 0 99990000 99970002 99990000 0 99980000 99970002 99980000 0 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 9999 10000 9998 </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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:39</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'81263254da979d8a',t:'MTY5NjY4MjI1OS4wMzQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1300"]
1220C
1220
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><span class="tex-font-style-sl">стандартный ввод</span></div><div class="output-file"><div class="property-title">вывод</div><span class="tex-font-style-sl">стандартный вывод</span></div></div><div><p>Миша и Аня сидят на скучном уроке. Чтобы хоть как-то скрасить ожидание перемены, они придумали интересную игру. Для игры необходима лишь строка $$$s$$$ и число $$$k$$$ ($$$0 \le k &lt; |s|$$$).</p><p>Игра начинается с того, что на строке $$$s$$$ отмечается подстрока длины 1, ее левая граница $$$l$$$ и правая граница $$$r$$$ равны $$$k$$$ (то есть вначале игры $$$l=r=k$$$). Далее игроки ходят по очереди, расширяя подстроку по следующим правилам:</p><ul><li> Игрок выбирает индексы $$$l^{\prime}$$$ и $$$r^{\prime}$$$ такие, что $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ и $$$s[l^{\prime}, r^{\prime}]$$$ лексикографически меньше $$$s[l, r]$$$. После этого изменяет значения $$$l$$$ и $$$r$$$ следующим образом: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$.</li><li> Аня ходит первой.</li><li> Проигрывает тот, кто не может сделать ход. </li></ul><p>Напомним, что подстрокой $$$s[l, r]$$$ ($$$l \le r$$$) строки $$$s$$$ будем называть непрерывную подпоследовательность символов начинающуюся в позиции $$$l$$$ и заканчивающуюся в позиции $$$r$$$. Например «<span class="tex-font-style-tt">ehn</span>» — подстрока ($$$s[3, 5]$$$) строки «<span class="tex-font-style-tt">aaaehnsvz</span>», а «<span class="tex-font-style-tt">ahz</span>» — нет.</p><p>Миша и Аня играли в игру так увлеченно, что не заметили как к ним подошел учитель. К большому удивлению обоих, он не стал их отчитывать, а сказал, что может определить победителя до начала игры, зная лишь $$$s$$$ и $$$k$$$!</p><p>К сожалению, Миша и Аня не разбираются в теории игр, поэтому попросили Вас написать программу, которая по заданной $$$s$$$ определяет победителя для всех возможных $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из единственной строки $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$), которая содержит исключительно строчные английские буквы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выходные данные должны содержать $$$|s|$$$ строк.</p><p>В строке номер $$$i$$$ выведите имя победителя игры (выведите <span class="tex-font-style-tt">Ann</span> или <span class="tex-font-style-tt">Mike</span>) со строкой $$$s$$$, для $$$k = i$$$, при условии, что Аня и Миша играют оптимально.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Mike Ann Ann Mike </pre></div><div class="input"><div class="title">Входные данные</div><pre> cba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Mike Mike Mike </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="0701ba346ecbc4c205dcc9dfbb713d49"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='0701ba346ecbc4c205dcc9dfbb713d49'>&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/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=%2Fcontest%2F1220%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='0701ba346ecbc4c205dcc9dfbb713d49'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='0701ba346ecbc4c205dcc9dfbb713d49'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='0701ba346ecbc4c205dcc9dfbb713d49'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415030"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='0701ba346ecbc4c205dcc9dfbb713d49'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415030"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_41947ad1ce3e2254af83f44bdfd2116f8abdaf1a"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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><span class="tex-font-style-sl">стандартный ввод</span></div><div class="output-file"><div class="property-title">вывод</div><span class="tex-font-style-sl">стандартный вывод</span></div></div><div><p>Миша и Аня сидят на скучном уроке. Чтобы хоть как-то скрасить ожидание перемены, они придумали интересную игру. Для игры необходима лишь строка $$$s$$$ и число $$$k$$$ ($$$0 \le k &lt; |s|$$$).</p><p>Игра начинается с того, что на строке $$$s$$$ отмечается подстрока длины 1, ее левая граница $$$l$$$ и правая граница $$$r$$$ равны $$$k$$$ (то есть вначале игры $$$l=r=k$$$). Далее игроки ходят по очереди, расширяя подстроку по следующим правилам:</p><ul><li> Игрок выбирает индексы $$$l^{\prime}$$$ и $$$r^{\prime}$$$ такие, что $$$l^{\prime} \le l$$$, $$$r^{\prime} \ge r$$$ и $$$s[l^{\prime}, r^{\prime}]$$$ лексикографически меньше $$$s[l, r]$$$. После этого изменяет значения $$$l$$$ и $$$r$$$ следующим образом: $$$l := l^{\prime}$$$, $$$r := r^{\prime}$$$.</li><li> Аня ходит первой.</li><li> Проигрывает тот, кто не может сделать ход. </li></ul><p>Напомним, что подстрокой $$$s[l, r]$$$ ($$$l \le r$$$) строки $$$s$$$ будем называть непрерывную подпоследовательность символов начинающуюся в позиции $$$l$$$ и заканчивающуюся в позиции $$$r$$$. Например «<span class="tex-font-style-tt">ehn</span>» — подстрока ($$$s[3, 5]$$$) строки «<span class="tex-font-style-tt">aaaehnsvz</span>», а «<span class="tex-font-style-tt">ahz</span>» — нет.</p><p>Миша и Аня играли в игру так увлеченно, что не заметили как к ним подошел учитель. К большому удивлению обоих, он не стал их отчитывать, а сказал, что может определить победителя до начала игры, зная лишь $$$s$$$ и $$$k$$$!</p><p>К сожалению, Миша и Аня не разбираются в теории игр, поэтому попросили Вас написать программу, которая по заданной $$$s$$$ определяет победителя для всех возможных $$$k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Входные данные состоят из единственной строки $$$s$$$ ($$$1 \leq |s| \leq 5 \cdot 10^5$$$), которая содержит исключительно строчные английские буквы.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выходные данные должны содержать $$$|s|$$$ строк.</p><p>В строке номер $$$i$$$ выведите имя победителя игры (выведите <span class="tex-font-style-tt">Ann</span> или <span class="tex-font-style-tt">Mike</span>) со строкой $$$s$$$, для $$$k = i$$$, при условии, что Аня и Миша играют оптимально.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> abba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Mike Ann Ann Mike </pre></div><div class="input"><div class="title">Входные данные</div><pre> cba </pre></div><div class="output"><div class="title">Выходные данные</div><pre> Mike Mike Mike </pre></div></div></div></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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:40</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'8126325e9eba4971',t:'MTY5NjY4MjI2MC40ODAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u0433\u0440\u044b, \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u0428\u043f\u0440\u0430\u0433\u0430-\u0413\u0440\u0430\u043d\u0434\u0438", "\u041f\u0440\u0435\u0444\u0438\u043a\u0441- \u0438 Z-\u0444\u0443\u043d\u043a\u0446\u0438\u0438, \u0441\u0443\u0444\u0444\u0438\u043a\u0441\u043d\u044b\u0435 \u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b, \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c \u041a\u043d\u0443\u0442\u0430-\u041c\u043e\u0440\u0440\u0438\u0441\u0430-\u041f\u0440\u0430\u0442\u0442\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0438\u0433\u0440\u044b", "\u0441\u0442\u0440\u043e\u043a\u0438", "*1300"]
1220D
1220
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>Мальчик Дима подарил Ульяне на день рождения множество $$$B$$$, состоящее из положительных целых чисел. Однако он не учел, что Ульяна терпеть не может множества, а больше всего на свете любит двудольные графы!</p><p>Ульяна уже была готова расстроиться, но её друг Леша сказал, что может построить неориентированный граф с помощью этого множества следующим образом: рассмотрим все целые числа как вершины графа и соединим ребрами все $$$i$$$ и $$$j$$$ такие, что $$$|i - j|$$$ принадлежит $$$B$$$.</p><p>К сожалению, граф, построенный по множеству $$$B$$$ не очень нравится Ульяне. Леша решил исправить ситуацию и хочет незаметно выкинуть из $$$B$$$ несколько чисел так, чтобы граф, построенный на новом множестве был двудольным. Сложность этой задачи заключается в том, что граф, с которым придется работать Леше, содержит бесконечное число вершин и ребер! Одному с такой задачей не справиться, поэтому Леша просит Вас о помощи. Напишите программу, которая удаляет из $$$B$$$ <span class="tex-font-style-bf">минимальное</span> по размеру подмножество чисел так, чтобы граф, построенный на оставшемся множестве стал двудольным.</p><p>Напомним, что граф называется двудольным, если вершины можно разбить на 2 множества так, что не существует ребер между вершинами из одного множествами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — размер множества $$$B$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$$$ — элементы множества $$$B$$$, все $$$b_i$$$ <span class="tex-font-style-bf">уникальны</span> (не повторяются)</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ — количество удаляемых элементов множества, а во второй строке выведите $$$k$$$ чисел через пробел — значения удаляемых элементов в любом порядке.</p><p>Если возможных ответов несколько, выведите любой</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="5b8e2660ef4d611c3b3473fd80cc1aff"/> <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="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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='5b8e2660ef4d611c3b3473fd80cc1aff'>&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%2F1220%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='5b8e2660ef4d611c3b3473fd80cc1aff'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='5b8e2660ef4d611c3b3473fd80cc1aff'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='5b8e2660ef4d611c3b3473fd80cc1aff'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415036"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5b8e2660ef4d611c3b3473fd80cc1aff'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415036"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" 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/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" 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/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_0eb507f7230f9ae04ac0b8a76ffb1de68bee9c71"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Мальчик Дима подарил Ульяне на день рождения множество $$$B$$$, состоящее из положительных целых чисел. Однако он не учел, что Ульяна терпеть не может множества, а больше всего на свете любит двудольные графы!</p><p>Ульяна уже была готова расстроиться, но её друг Леша сказал, что может построить неориентированный граф с помощью этого множества следующим образом: рассмотрим все целые числа как вершины графа и соединим ребрами все $$$i$$$ и $$$j$$$ такие, что $$$|i - j|$$$ принадлежит $$$B$$$.</p><p>К сожалению, граф, построенный по множеству $$$B$$$ не очень нравится Ульяне. Леша решил исправить ситуацию и хочет незаметно выкинуть из $$$B$$$ несколько чисел так, чтобы граф, построенный на новом множестве был двудольным. Сложность этой задачи заключается в том, что граф, с которым придется работать Леше, содержит бесконечное число вершин и ребер! Одному с такой задачей не справиться, поэтому Леша просит Вас о помощи. Напишите программу, которая удаляет из $$$B$$$ <span class="tex-font-style-bf">минимальное</span> по размеру подмножество чисел так, чтобы граф, построенный на оставшемся множестве стал двудольным.</p><p>Напомним, что граф называется двудольным, если вершины можно разбить на 2 множества так, что не существует ребер между вершинами из одного множествами.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — размер множества $$$B$$$.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$b_1, b_2, \ldots, b_n ~ (1 \leqslant b_i \leqslant 10^{18})$$$ — элементы множества $$$B$$$, все $$$b_i$$$ <span class="tex-font-style-bf">уникальны</span> (не повторяются)</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите целое число $$$k$$$ — количество удаляемых элементов множества, а во второй строке выведите $$$k$$$ чисел через пробел — значения удаляемых элементов в любом порядке.</p><p>Если возможных ответов несколько, выведите любой</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 1 2 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 2 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 2 2 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 </pre></div></div></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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 10:45: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:'8124861cfb4e7b73',t:'MTY5NjY2NDcxOC45ODAwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0422\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b: \u0444\u0443\u043d\u043a\u0446\u0438\u044f \u042d\u0439\u043b\u0435\u0440\u0430, \u041d\u041e\u0414, \u0434\u0435\u043b\u0438\u043c\u043e\u0441\u0442\u044c \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u0442\u0435\u043e\u0440\u0438\u044f \u0447\u0438\u0441\u0435\u043b", "*1900"]
1220E
1220
E
ru
E. Туризм
<div class="problem-statement"><div class="header"><div class="title">E. Туризм</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Лёша решил отправиться в туристическую поездку по стране.</p><p>Для простоты стоит считать, что в стране есть $$$n$$$ городов и $$$m$$$ двусторонних дорог, которые их соединяют. Лёша живёт в городе $$$s$$$ и изначально находится в нём. Каждый город в стране по своему хорош и чтобы сравнивать города между собой, Лёша поставил каждому городу оценку $$$w_i$$$, которая тем больше, чем интереснее город кажется Лёше.</p><p>Лёша считает, что его поездка по стране будет интересной только в том случае, если ему ни в какой момент времени не придётся ехать назад по дороге, по которой он только что проехал. Другими словами, если Лёша переехал из города $$$u$$$ в город $$$v$$$, следующим в своей поездке Лёша может выбрать любой город, соединённый с $$$v$$$ дорогой, кроме города $$$u$$$.</p><p>Помогите Лёше спланировать поездку так, чтобы сумма оценок по всем посещённым им городам была максимальна. Считайте, что оценка любого посещённого города учитывается в сумме только один раз, даже если город был посещён не единожды.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$m$$$, ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) — количество городов и дорог в стране.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$) — оценки всех городов.</p><p>Следующие $$$m$$$ строк содержат описание дорог. Каждая из $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u, v \le n$$$) — города, которые соединяются дорогой.</p><p>Гарантируется, что любые два города соединены не более, чем одной дорогой, никакой город не соединён дорогой с самим собой, а также что из любого города можно добраться в любой другой по дорогам.</p><p>Последняя строка содержит одно целое число $$$s$$$ ($$$1 \le s \le n$$$) — номер стартового города.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальную сумму оценок посещённых городов, которую можно получить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 7 2 2 8 6 9 1 2 1 3 2 4 3 2 4 5 2 5 1 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 27 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 12 1 7 1 9 3 3 6 30 1 10 1 2 1 3 3 5 5 7 2 3 5 4 6 9 4 6 3 7 6 8 9 4 9 10 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 61 </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="bb7bae34cba8d514959db2410c690aa5"/> <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="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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='bb7bae34cba8d514959db2410c690aa5'>&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%2F1220%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='bb7bae34cba8d514959db2410c690aa5'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='bb7bae34cba8d514959db2410c690aa5'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='bb7bae34cba8d514959db2410c690aa5'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415038"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='bb7bae34cba8d514959db2410c690aa5'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415038"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" 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/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" 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/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_969fb41af8012f17aca333abb7b87ca97ee0ea44"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Лёша решил отправиться в туристическую поездку по стране.</p><p>Для простоты стоит считать, что в стране есть $$$n$$$ городов и $$$m$$$ двусторонних дорог, которые их соединяют. Лёша живёт в городе $$$s$$$ и изначально находится в нём. Каждый город в стране по своему хорош и чтобы сравнивать города между собой, Лёша поставил каждому городу оценку $$$w_i$$$, которая тем больше, чем интереснее город кажется Лёше.</p><p>Лёша считает, что его поездка по стране будет интересной только в том случае, если ему ни в какой момент времени не придётся ехать назад по дороге, по которой он только что проехал. Другими словами, если Лёша переехал из города $$$u$$$ в город $$$v$$$, следующим в своей поездке Лёша может выбрать любой город, соединённый с $$$v$$$ дорогой, кроме города $$$u$$$.</p><p>Помогите Лёше спланировать поездку так, чтобы сумма оценок по всем посещённым им городам была максимальна. Считайте, что оценка любого посещённого города учитывается в сумме только один раз, даже если город был посещён не единожды.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит два целых числа $$$n$$$, $$$m$$$, ($$$1 \le n \le 2 \cdot 10^5$$$, $$$0 \le m \le 2 \cdot 10^5$$$) — количество городов и дорог в стране.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$w_1, w_2, \ldots, w_n$$$ ($$$0 \le w_i \le 10^9$$$) — оценки всех городов.</p><p>Следующие $$$m$$$ строк содержат описание дорог. Каждая из $$$m$$$ строк содержит два целых числа $$$u$$$ и $$$v$$$ ($$$1 \le u, v \le n$$$) — города, которые соединяются дорогой.</p><p>Гарантируется, что любые два города соединены не более, чем одной дорогой, никакой город не соединён дорогой с самим собой, а также что из любого города можно добраться в любой другой по дорогам.</p><p>Последняя строка содержит одно целое число $$$s$$$ ($$$1 \le s \le n$$$) — номер стартового города.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — максимальную сумму оценок посещённых городов, которую можно получить.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 5 7 2 2 8 6 9 1 2 1 3 2 4 3 2 4 5 2 5 1 5 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 27 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 10 12 1 7 1 9 3 3 6 30 1 10 1 2 1 3 3 5 5 7 2 3 5 4 6 9 4 6 3 7 6 8 9 4 9 10 6 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 61 </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 10:45: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:'812486254cca75b7',t:'MTY5NjY2NDcyMC4yOTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0413\u0440\u0430\u0444\u044b", "\u0414\u0435\u0440\u0435\u0432\u044c\u044f", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u041f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0421\u0438\u0441\u0442\u0435\u043c\u0430 \u043d\u0435\u043f\u0435\u0440\u0435\u0441\u0435\u043a\u0430\u044e\u0449\u0438\u0445\u0441\u044f \u043c\u043d\u043e\u0436\u0435\u0441\u0442\u0432", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0440\u0430\u0444\u044b", "\u0434\u0435\u0440\u0435\u0432\u044c\u044f", "\u0434\u043f", "\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043f\u043e\u0438\u0441\u043a \u0432 \u0433\u043b\u0443\u0431\u0438\u043d\u0443 \u0438 \u043f\u043e\u0434\u043e\u0431\u043d\u043e\u0435", "\u0441\u043d\u043c", "*2200"]
1220F
1220
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$$$ вершинах.</p><p>Сегодня он решил вырастить подвешенное бинарное дерево. Бинарным деревом называется дерево, в котором у каждой вершины не больше двух сыновей. К счастью, у Леши еще с прошлого дня рождения завалялась перестановка чисел от $$$1$$$ до $$$n$$$, поэтому он решил вырастить дерево по этой перестановке. Для этого он совершает следующий процесс: находит минимум в перестановке, создает соответствующую ему вершину и делает ее корнем дерева. После этого перестановка разделяется на две части: все, что левее минимального элемента, и все, что правее. Минимумы на левой и правой части становятся левыми и правыми сыновьями корня соответственно, после чего на левой и правой части производится рекурсивно тот же процесс.</p><p>Теперь Леша хочет вырастить целый лес деревьев: по одному дереву на каждый циклический сдвиг перестановки. Ему интересно, при каком циклическом сдвиге глубина полученного дерева будет минимальной. Но, к сожалению, выращивание леса — дело долгое, а ответ интересен Леше прямо сейчас. Поможете ему?</p><p>Напомним, что циклическим сдвигом перестановки $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ на $$$k$$$ элементов влево называется перестановка $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — длина перестановки.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, при этом гарантируется, что каждое число встречается ровно один раз. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Через пробел выведите два числа: минимальная глубина дерева, которую можно получить, и на сколько нужно циклически сдвинуть перестановку влево, чтобы получить дерево минимальной глубины. Величина сдвига должна быть числом от $$$0$$$ до $$$n - 1$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображены все возможные деревья для перестановки из примера, а рядом с ними написаны циклические сдвиги, из которых они получаются.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/617ffdeed5a9d33101e9c3573e18cf48f73c27f8.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px"/></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="530c8127282dccb69a0e8b3f7bdc2b7e"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - F - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='530c8127282dccb69a0e8b3f7bdc2b7e'>&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/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=%2Fcontest%2F1220%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='530c8127282dccb69a0e8b3f7bdc2b7e'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='530c8127282dccb69a0e8b3f7bdc2b7e'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='530c8127282dccb69a0e8b3f7bdc2b7e'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415037"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='530c8127282dccb69a0e8b3f7bdc2b7e'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415037"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_1f3d0088459c9ba43ecf3299b068dd54cde13222"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ вершинах.</p><p>Сегодня он решил вырастить подвешенное бинарное дерево. Бинарным деревом называется дерево, в котором у каждой вершины не больше двух сыновей. К счастью, у Леши еще с прошлого дня рождения завалялась перестановка чисел от $$$1$$$ до $$$n$$$, поэтому он решил вырастить дерево по этой перестановке. Для этого он совершает следующий процесс: находит минимум в перестановке, создает соответствующую ему вершину и делает ее корнем дерева. После этого перестановка разделяется на две части: все, что левее минимального элемента, и все, что правее. Минимумы на левой и правой части становятся левыми и правыми сыновьями корня соответственно, после чего на левой и правой части производится рекурсивно тот же процесс.</p><p>Теперь Леша хочет вырастить целый лес деревьев: по одному дереву на каждый циклический сдвиг перестановки. Ему интересно, при каком циклическом сдвиге глубина полученного дерева будет минимальной. Но, к сожалению, выращивание леса — дело долгое, а ответ интересен Леше прямо сейчас. Поможете ему?</p><p>Напомним, что циклическим сдвигом перестановки $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ на $$$k$$$ элементов влево называется перестановка $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит целое число $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — длина перестановки.</p><p>Вторая строка содержит $$$n$$$ целых чисел $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, при этом гарантируется, что каждое число встречается ровно один раз. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Через пробел выведите два числа: минимальная глубина дерева, которую можно получить, и на сколько нужно циклически сдвинуть перестановку влево, чтобы получить дерево минимальной глубины. Величина сдвига должна быть числом от $$$0$$$ до $$$n - 1$$$. Если возможных ответов несколько, выведите любой.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 4 1 2 3 4 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 3 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>На картинке ниже изображены все возможные деревья для перестановки из примера, а рядом с ними написаны циклические сдвиги, из которых они получаются.</p><p><img class="tex-graphics" src="https://espresso.codeforces.com/617ffdeed5a9d33101e9c3573e18cf48f73c27f8.png" style="max-width: 100.0%;max-height: 100.0%;" width="378px" /></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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:41</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'81263267ae909d37',t:'MTY5NjY4MjI2MS44NjkwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*2700"]
1220G
1220
G
ru
G. Геолокация
<div class="problem-statement"><div class="header"><div class="title">G. Геолокация</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>2 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы работаете на компанию Гриззл в Пауни, штат Индиана.</p><p>Недавно возле Пауни открылся новый национальный парк и перед вами была поставлена задача разработать систему геопозиционирования, чтобы люди в нём не заблудились. Концепция, которую вы разработали, инновационна и минималистична. В парке будет установлено $$$n$$$ антенн. Когда кто-то захочет узнать своё местонахождение, их гриззлфон свяжется с антеннами и узнает расстояния от текущей позиции пользователя до всех антенн.</p><p>Зная эти расстояния и местонахождение антенн, восстановить местонахождение пользователя должно быть просто... Ведь так? Ну, почти. Единственная проблема заключается в том, что вы не знаете, какой антенне соответствует каждое из расстояний. Ваша задача – определить местонахождение пользователя, зная только местонахождение всех антенн и мультимножество расстояний до них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит единственное целое число $$$n$$$ ($$$2 \leq n \leq 10^5$$$), количество антенн.</p><p>Следующие $$$n$$$ строк содержат координаты антенн, $$$i$$$-я строка содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$0 \leq x_i,y_i \leq 10^8$$$). Гарантируется, что все местонахождения антенны различны.</p><p>Следующая строка содержит единственное целое число $$$m$$$ ($$$1 \leq n \cdot m \leq 10^5$$$), количество запросов на определение местонахождения пользователя.</p><p>Следующие $$$m$$$ строк содержат $$$n$$$ целых чисел $$$0 \leq d_1 \leq d_2 \leq \dots \leq d_n \leq 2 \cdot 10^{16}$$$ каждая. Эти числа образуют мультимножество <span class="tex-font-style-bf">квадратов</span> расстояний от местонахождения пользователя $$$(x;y)$$$ до всех антенн.</p><p>Для всех тестов, кроме примеров, гарантируется, что во всех запросах местонахождения пользователя $$$(x;y)$$$ были выбраны равномерно и независимо друг от друга среди всех возможных целочисленных точек, таких что $$$0 \leq x, y \leq 10^8$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите сначала число $$$k$$$ – количество возможных местонахождений пользователя, а затем список из этих точек в лексикографическом порядке.</p><p>Гарантируется, что сумма $$$k$$$ по всем запросам не превосходит $$$10^6$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 0 1 1 0 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 0 0 1 1 0 1 1 2 0 1 1 2 2 5 5 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 0 0 1 1 0 1 1 4 -1 -1 -1 2 2 -1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Как можно видеть во втором примере — хотя местонахождение пользователя и выбирается так, чтобы иметь неотрицательные координаты, вам необходимо вывести все возможные целочисленные координаты.</p></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="944f04a3334269980b651153ec40c8fe"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - G - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="218f2eabb6f9b2cf50d051c0b0359636651e6f28"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='944f04a3334269980b651153ec40c8fe'>&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/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=%2Fcontest%2F1220%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='944f04a3334269980b651153ec40c8fe'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1220">Codeforces Round 586 (Div. 1 + 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='944f04a3334269980b651153ec40c8fe'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1220/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *3400 </span> </div> <div style="clear:both;text-align:right;font-size:1.1rem;"> <span title="Пожалуйста, войдите в систему" class="notice">Нет прав на редактирование</span> </div> </div> </div> <form id="addTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='944f04a3334269980b651153ec40c8fe'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415039"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='944f04a3334269980b651153ec40c8fe'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415039"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69838" title="Codeforces Round 586 (отбор на кружок ФПМИ и ЦРИТО)" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9351:9352" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69899" title="Codeforces Round #586 Editorial" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9376:9377" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1220">Задачи</a></li> <li><a href="/contest/1220/submit">Отослать</a></li> <li><a href="/contest/1220/my">Мои посылки</a></li> <li><a href="/contest/1220/status">Статус</a></li> <li><a href="/contest/1220/hacks">Взломы</a></li> <li><a href="/contest/1220/room/1">Комната</a></li> <li><a href="/contest/1220/standings">Положение</a></li> <li><a href="/contest/1220/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_b095f84cd06760eabb85995e35474536951b92dc"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Вы работаете на компанию Гриззл в Пауни, штат Индиана.</p><p>Недавно возле Пауни открылся новый национальный парк и перед вами была поставлена задача разработать систему геопозиционирования, чтобы люди в нём не заблудились. Концепция, которую вы разработали, инновационна и минималистична. В парке будет установлено $$$n$$$ антенн. Когда кто-то захочет узнать своё местонахождение, их гриззлфон свяжется с антеннами и узнает расстояния от текущей позиции пользователя до всех антенн.</p><p>Зная эти расстояния и местонахождение антенн, восстановить местонахождение пользователя должно быть просто... Ведь так? Ну, почти. Единственная проблема заключается в том, что вы не знаете, какой антенне соответствует каждое из расстояний. Ваша задача – определить местонахождение пользователя, зная только местонахождение всех антенн и мультимножество расстояний до них.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка ввода содержит единственное целое число $$$n$$$ ($$$2 \leq n \leq 10^5$$$), количество антенн.</p><p>Следующие $$$n$$$ строк содержат координаты антенн, $$$i$$$-я строка содержит два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$0 \leq x_i,y_i \leq 10^8$$$). Гарантируется, что все местонахождения антенны различны.</p><p>Следующая строка содержит единственное целое число $$$m$$$ ($$$1 \leq n \cdot m \leq 10^5$$$), количество запросов на определение местонахождения пользователя.</p><p>Следующие $$$m$$$ строк содержат $$$n$$$ целых чисел $$$0 \leq d_1 \leq d_2 \leq \dots \leq d_n \leq 2 \cdot 10^{16}$$$ каждая. Эти числа образуют мультимножество <span class="tex-font-style-bf">квадратов</span> расстояний от местонахождения пользователя $$$(x;y)$$$ до всех антенн.</p><p>Для всех тестов, кроме примеров, гарантируется, что во всех запросах местонахождения пользователя $$$(x;y)$$$ были выбраны равномерно и независимо друг от друга среди всех возможных целочисленных точек, таких что $$$0 \leq x, y \leq 10^8$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Для каждого запроса выведите сначала число $$$k$$$ – количество возможных местонахождений пользователя, а затем список из этих точек в лексикографическом порядке.</p><p>Гарантируется, что сумма $$$k$$$ по всем запросам не превосходит $$$10^6$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 0 0 0 1 1 0 1 1 1 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 1 1 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 0 0 0 1 1 0 1 1 2 0 1 1 2 2 5 5 8 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 0 0 0 1 1 0 1 1 4 -1 -1 -1 2 2 -1 2 2 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Как можно видеть во втором примере — хотя местонахождение пользователя и выбирается так, чтобы иметь неотрицательные координаты, вам необходимо вывести все возможные целочисленные координаты.</p></div></div><p> </p></div> </div> <script> $(function () { Codeforces.addMathJaxListener(function () { let $problem = $("div[problemindex=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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:43</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'812632705c1216f7',t:'MTY5NjY4MjI2My4xOTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0433\u0435\u043e\u043c\u0435\u0442\u0440\u0438\u044f", "*3400"]
1221A
1221
A
ru
A. Игра 2048
<div class="problem-statement"><div class="header"><div class="title">A. Игра 2048</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">2048</span>. Изначально у вас есть набор $$$s$$$, состоящий из $$$n$$$ чисел. Все числа из этого набора являются степенью двойки. </p><p>Вы можете совершать любое количество (возможно, нулевое) операций с этим набором чисел.</p><p>Во время каждой операции вы выбираете два <span class="tex-font-style-bf">равных</span> числа из $$$s$$$, удаляете их из набора $$$s$$$ и добавляете в $$$s$$$ число, равное их сумме.</p><p>Например, если $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$, и вы выберете числа $$$2$$$ и $$$2$$$, то набор превратится в $$$\{1, 1, 1, 4, 4, 2\}$$$.</p><p>Вы выиграете, если число $$$2048$$$ окажется в вашем наборе. Например, если $$$s = \{1024, 512, 512, 4\}$$$ вы можете выиграть следующим образом: выберите $$$512$$$ и $$$512$$$, и ваш набор превратится в $$$\{1024, 1024, 4\}$$$. Затем вы можете выбрать числа $$$1024$$$ и $$$1024$$$, и ваш набор превратится в $$$\{2048, 4\}$$$. </p><p>Определите, можете ли вы выиграть в этой игре.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — количество чисел в наборе.</p><p>Вторая строка каждого запроса содержит $$$n$$$ чисел $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — описание вашего набора чисел. Гарантируется, что все числа в наборе являются степенью двойки. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите <span class="tex-font-style-tt">YES</span> если вы можете получить число $$$2048$$$ в вашем наборе, и <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> 6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO NO YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете выбрать числа $$$512$$$ и $$$512$$$, и $$$s$$$ превратится в $$$\{1024, 64, 1024\}$$$. А затем вы выбираете числа $$$1024$$$ и $$$1024$$$, после этого набор $$$s$$$ превратится в $$$\{2048, 64\}$$$.</p><p>Во втором запросе набор $$$s$$$ содержит число $$$2048$$$ изначально.</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="9caa6c57712dd8f6ea664e16eef1ae82"/> <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="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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='9caa6c57712dd8f6ea664e16eef1ae82'>&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%2F1221%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='9caa6c57712dd8f6ea664e16eef1ae82'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='9caa6c57712dd8f6ea664e16eef1ae82'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='9caa6c57712dd8f6ea664e16eef1ae82'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415607"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='9caa6c57712dd8f6ea664e16eef1ae82'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415607"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" 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/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" 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/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_758ce5379503c84f918c5f3f0ba715529e3ecbfe"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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. Игра 2048</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">2048</span>. Изначально у вас есть набор $$$s$$$, состоящий из $$$n$$$ чисел. Все числа из этого набора являются степенью двойки. </p><p>Вы можете совершать любое количество (возможно, нулевое) операций с этим набором чисел.</p><p>Во время каждой операции вы выбираете два <span class="tex-font-style-bf">равных</span> числа из $$$s$$$, удаляете их из набора $$$s$$$ и добавляете в $$$s$$$ число, равное их сумме.</p><p>Например, если $$$s = \{1, 2, 1, 1, 4, 2, 2\}$$$, и вы выберете числа $$$2$$$ и $$$2$$$, то набор превратится в $$$\{1, 1, 1, 4, 4, 2\}$$$.</p><p>Вы выиграете, если число $$$2048$$$ окажется в вашем наборе. Например, если $$$s = \{1024, 512, 512, 4\}$$$ вы можете выиграть следующим образом: выберите $$$512$$$ и $$$512$$$, и ваш набор превратится в $$$\{1024, 1024, 4\}$$$. Затем вы можете выбрать числа $$$1024$$$ и $$$1024$$$, и ваш набор превратится в $$$\{2048, 4\}$$$. </p><p>Определите, можете ли вы выиграть в этой игре.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 100$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$1 \le n \le 100$$$) — количество чисел в наборе.</p><p>Вторая строка каждого запроса содержит $$$n$$$ чисел $$$s_1, s_2, \dots, s_n$$$ ($$$1 \le s_i \le 2^{29}$$$) — описание вашего набора чисел. Гарантируется, что все числа в наборе являются степенью двойки. </p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите <span class="tex-font-style-tt">YES</span> если вы можете получить число $$$2048$$$ в вашем наборе, и <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> 6 4 1024 512 64 512 1 2048 3 64 512 2 2 4096 4 7 2048 2 2048 2048 2048 2048 2048 2 2048 4096 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES YES NO NO YES YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вы можете выбрать числа $$$512$$$ и $$$512$$$, и $$$s$$$ превратится в $$$\{1024, 64, 1024\}$$$. А затем вы выбираете числа $$$1024$$$ и $$$1024$$$, после этого набор $$$s$$$ превратится в $$$\{2048, 64\}$$$.</p><p>Во втором запросе набор $$$s$$$ содержит число $$$2048$$$ изначально.</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 10:45: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:'8124863d384875b7',t:'MTY5NjY2NDcyNC4yNTYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0416\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0436\u0430\u0434\u043d\u044b\u0435 \u0430\u043b\u0433\u043e\u0440\u0438\u0442\u043c\u044b", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*1000"]
1221B
1221
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$$$ рядами и $$$n$$$ столбцами. Изначально все клетки пусты, и в каждую из них вы должны поставить либо белого коня, либо черного коня.</p><p>Конь — шахматная фигура, которая может переместиться из клетки ($$$x_2$$$, $$$y_2$$$) в клетку ($$$x_1$$$, $$$y_1$$$), если одно из следующих условий выполняется:</p><ul> <li> $$$|x_1 - x_2| = 2$$$ и $$$|y_1 - y_2| = 1$$$, или </li><li> $$$|x_1 - x_2| = 1$$$ и $$$|y_1 - y_2| = 2$$$. </li></ul><p>Ниже приведены примеры, как может ходить (и атаковать) конь. На каждой из нижеприведенных картинок, если конь находится в синей клетке, он атакует все красные клетки (и только их).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3bd905307bf319355b39873e617ef876d5b18327.png" style="max-width: 100.0%;max-height: 100.0%;"/> </center><p><span class="tex-font-style-it">Дуэлью коней</span> назовем пару коней <span class="tex-font-style-bf">разных</span> цветов, атакующих друг друга. Вам нужно поставить коня (либо белого, либо черного) в каждую клетку так, чтобы количество дуэлей было максимально возможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке задано одно целое $$$n$$$ ($$$3 \le n \le 100$$$) — количество рядов (и столбцов), из которых состоит шахматная доска.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк, по $$$n$$$ символов в каждой. $$$j$$$-й символ в $$$i$$$-й строке должен быть <span class="tex-font-style-tt">W</span>, если в клетке ($$$i$$$, $$$j$$$) должен стоять белый конь, или <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> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> WBW BBB WBW </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$8$$$ дуэлей:</p><ol> <li> белый конь в ($$$1$$$, $$$1$$$) атакует черного коня в ($$$3$$$, $$$2$$$); </li><li> белый конь в ($$$1$$$, $$$1$$$) атакует черного коня в ($$$2$$$, $$$3$$$); </li><li> белый конь в ($$$1$$$, $$$3$$$) атакует черного коня в ($$$3$$$, $$$2$$$); </li><li> белый конь в ($$$1$$$, $$$3$$$) атакует черного коня в ($$$2$$$, $$$1$$$); </li><li> белый конь в ($$$3$$$, $$$1$$$) атакует черного коня в ($$$1$$$, $$$2$$$); </li><li> белый конь в ($$$3$$$, $$$1$$$) атакует черного коня в ($$$2$$$, $$$3$$$); </li><li> белый конь в ($$$3$$$, $$$3$$$) атакует черного коня в ($$$1$$$, $$$2$$$); </li><li> белый конь в ($$$3$$$, $$$3$$$) атакует черного коня в ($$$2$$$, $$$1$$$). </li></ol></div></div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html lang="ru"> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="X-Csrf-Token" content="3af67eac2f020e54403cc5c3ea4005ca"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - B - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='3af67eac2f020e54403cc5c3ea4005ca'>&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/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=%2Fcontest%2F1221%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='3af67eac2f020e54403cc5c3ea4005ca'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='3af67eac2f020e54403cc5c3ea4005ca'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='3af67eac2f020e54403cc5c3ea4005ca'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415608"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3af67eac2f020e54403cc5c3ea4005ca'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415608"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f02029655e092435a51acc8e0e9b6aaf1c0fda5c"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ рядами и $$$n$$$ столбцами. Изначально все клетки пусты, и в каждую из них вы должны поставить либо белого коня, либо черного коня.</p><p>Конь — шахматная фигура, которая может переместиться из клетки ($$$x_2$$$, $$$y_2$$$) в клетку ($$$x_1$$$, $$$y_1$$$), если одно из следующих условий выполняется:</p><ul> <li> $$$|x_1 - x_2| = 2$$$ и $$$|y_1 - y_2| = 1$$$, или </li><li> $$$|x_1 - x_2| = 1$$$ и $$$|y_1 - y_2| = 2$$$. </li></ul><p>Ниже приведены примеры, как может ходить (и атаковать) конь. На каждой из нижеприведенных картинок, если конь находится в синей клетке, он атакует все красные клетки (и только их).</p><center> <img class="tex-graphics" src="https://espresso.codeforces.com/3bd905307bf319355b39873e617ef876d5b18327.png" style="max-width: 100.0%;max-height: 100.0%;" /> </center><p><span class="tex-font-style-it">Дуэлью коней</span> назовем пару коней <span class="tex-font-style-bf">разных</span> цветов, атакующих друг друга. Вам нужно поставить коня (либо белого, либо черного) в каждую клетку так, чтобы количество дуэлей было максимально возможно.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В единственной строке задано одно целое $$$n$$$ ($$$3 \le n \le 100$$$) — количество рядов (и столбцов), из которых состоит шахматная доска.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$n$$$ строк, по $$$n$$$ символов в каждой. $$$j$$$-й символ в $$$i$$$-й строке должен быть <span class="tex-font-style-tt">W</span>, если в клетке ($$$i$$$, $$$j$$$) должен стоять белый конь, или <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> 3 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> WBW BBB WBW </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере $$$8$$$ дуэлей:</p><ol> <li> белый конь в ($$$1$$$, $$$1$$$) атакует черного коня в ($$$3$$$, $$$2$$$); </li><li> белый конь в ($$$1$$$, $$$1$$$) атакует черного коня в ($$$2$$$, $$$3$$$); </li><li> белый конь в ($$$1$$$, $$$3$$$) атакует черного коня в ($$$3$$$, $$$2$$$); </li><li> белый конь в ($$$1$$$, $$$3$$$) атакует черного коня в ($$$2$$$, $$$1$$$); </li><li> белый конь в ($$$3$$$, $$$1$$$) атакует черного коня в ($$$1$$$, $$$2$$$); </li><li> белый конь в ($$$3$$$, $$$1$$$) атакует черного коня в ($$$2$$$, $$$3$$$); </li><li> белый конь в ($$$3$$$, $$$3$$$) атакует черного коня в ($$$1$$$, $$$2$$$); </li><li> белый конь в ($$$3$$$, $$$3$$$) атакует черного коня в ($$$2$$$, $$$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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:44</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'81263278a84b1498',t:'MTY5NjY4MjI2NC42MzYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1100"]
1221C
1221
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>Возможно вы уже знаете, что обычная команда для ICPC состоит из ровно трех человек. Однако для идеальной команды необходимо нечто большее. У студента может быть некоторая специализация: кодер или математик. <span class="tex-font-style-bf">Она/он может не иметь специализации, но иметь обе сразу не может.</span></p><p>Команда считается идеальной, когда в нее входит хотя бы один кодер, хотя бы один математик, и она состоит из ровно трех человек.</p><p>Вы тренер в очень большом университете и Вы знаете, что $$$c$$$ из Ваших студентов — кодеры, $$$m$$$ — математики и $$$x$$$ не имеют никакой специализации.</p><p>Какое наибольшее число полных идеальных команд Вы можете из них составить?</p><p>Обратите внимание, что некоторые студенты могут остаться без команды, и каждый студент может входить не более чем в одну команду.</p><p>Вам также необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество запросов.</p><p>В каждой из следующих $$$q$$$ строк записаны три целых числа $$$c$$$, $$$m$$$ и $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — количество кодеров, математиков и студентов без специализации в университете, соответственно.</p><p>Обратите внимание, что ни один студент не является кодером и математиком одновременно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — $$$i$$$-е из них должно быть ответом на $$$i$$$-й запрос в том же порядке, в которым запросы следуют во входных данных. Ответ равен наибольшему числу полных идеальных команд, которые Вы можете составить из Ваших студентов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 1 1 3 6 0 0 0 0 0 1 1 10 1 10 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 0 0 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере команды составляются следующим образом:</p><ol> <li> единственная команда состоит из 1 кодера, 1 математика и 1 без специализации; </li><li> все три команды состоят из 1 кодера и 2 математиков; </li><li> нельзя составить ни одной команды; </li><li> нельзя составить ни одной команды; </li><li> одна команда состоит из 1 кодера, 1 математика и 1 без специализации, остальные не могут образовать команду; </li><li> одна команда состоит из 1 кодера, 1 математика и 1 без специализации, одна из 2 кодеров и 1 математика и одна из 1 кодера и 2 математиков. </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="b4cef778f60a19015a30bd7643a36719"/> <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 = "ru"; window.standaloneContest = false; function adjustViewport() { var screenWidthPx = Math.min($(window).width(), window.screen.width); var siteWidthPx = 1100; // min width of site var ratio = Math.min(screenWidthPx / siteWidthPx, 1.0); var viewport = "width=device-width, initial-scale=" + ratio; $('#viewport').attr('content', viewport); var style = $('<style>html * { max-height: 1000000px; }</style>'); $('html > head').append(style); } if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) { adjustViewport(); } /* Protection against trailing dot in domain. */ let hostLength = window.location.host.length; if (hostLength > 1 && window.location.host[hostLength - 1] === '.') { window.location = window.location.protocol + "//" + window.location.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="Задача - C - Codeforces"/> <meta property="og:description" content=""/> <meta property="og:site_name" content="Codeforces"/> <meta name="cc" content="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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/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" /> <link rel="stylesheet" href="//codeforces.org/s/81027/css/sidebar-menu.css" type="text/css" charset="utf-8" /> <!-- MathJax --> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ tex2jax: {inlineMath: [['$$$','$$$']], displayMath: [['$$$$$$','$$$$$$']]} }); MathJax.Hub.Register.StartupHook("End", function () { Codeforces.runMathJaxListeners(); }); </script> <script type="text/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/ru/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-ru.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]--> <script type="text/javascript" src="//codeforces.org/s/81027/js/jquery.datepick-ru.js"></script> </head> <body class=" "><span style='display:none;' class='csrf-token' data-csrf='b4cef778f60a19015a30bd7643a36719'>&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/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=%2Fcontest%2F1221%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='b4cef778f60a19015a30bd7643a36719'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='b4cef778f60a19015a30bd7643a36719'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b4cef778f60a19015a30bd7643a36719'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415609"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b4cef778f60a19015a30bd7643a36719'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415609"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" resourceName="Анонс" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> <li> <span> <a href="/blog/entry/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" resourceName="Разбор задач" resourceManual="true" src="//codeforces.org/s/81027/images/icons/close-10x10.png" style="position: relative;bottom: -1px;left: 1px;cursor: pointer;"/> </span> <div style="clear: both;"></div> </li> </ul> </div></div> <div id="pageContent" class="content-with-sidebar"> <div class="second-level-menu"> <ul class="second-level-menu-list"> <li class="current selectedLava"><a href="/contest/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_3220dd39baf723b7553927edfd8511aa2d5863ad"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>Возможно вы уже знаете, что обычная команда для ICPC состоит из ровно трех человек. Однако для идеальной команды необходимо нечто большее. У студента может быть некоторая специализация: кодер или математик. <span class="tex-font-style-bf">Она/он может не иметь специализации, но иметь обе сразу не может.</span></p><p>Команда считается идеальной, когда в нее входит хотя бы один кодер, хотя бы один математик, и она состоит из ровно трех человек.</p><p>Вы тренер в очень большом университете и Вы знаете, что $$$c$$$ из Ваших студентов — кодеры, $$$m$$$ — математики и $$$x$$$ не имеют никакой специализации.</p><p>Какое наибольшее число полных идеальных команд Вы можете из них составить?</p><p>Обратите внимание, что некоторые студенты могут остаться без команды, и каждый студент может входить не более чем в одну команду.</p><p>Вам также необходимо ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке записано одно целое число $$$q$$$ ($$$1 \le q \le 10^4$$$) — количество запросов.</p><p>В каждой из следующих $$$q$$$ строк записаны три целых числа $$$c$$$, $$$m$$$ и $$$x$$$ ($$$0 \le c, m, x \le 10^8$$$) — количество кодеров, математиков и студентов без специализации в университете, соответственно.</p><p>Обратите внимание, что ни один студент не является кодером и математиком одновременно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите $$$q$$$ чисел — $$$i$$$-е из них должно быть ответом на $$$i$$$-й запрос в том же порядке, в которым запросы следуют во входных данных. Ответ равен наибольшему числу полных идеальных команд, которые Вы можете составить из Ваших студентов.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 1 1 1 3 6 0 0 0 0 0 1 1 10 1 10 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 1 3 0 0 1 3 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом примере команды составляются следующим образом:</p><ol> <li> единственная команда состоит из 1 кодера, 1 математика и 1 без специализации; </li><li> все три команды состоят из 1 кодера и 2 математиков; </li><li> нельзя составить ни одной команды; </li><li> нельзя составить ни одной команды; </li><li> одна команда состоит из 1 кодера, 1 математика и 1 без специализации, остальные не могут образовать команду; </li><li> одна команда состоит из 1 кодера, 1 математика и 1 без специализации, одна из 2 кодеров и 1 математика и одна из 1 кодера и 2 математиков. </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/81027"); $("#facebox .diff-popup").html(result["diff"]); } }, "json"); }); } } else { Codeforces.putToStorageTtl(uuid, statementText, 6 * 60 * 60); } }); }); </script> <script type="text/javascript"> $(document).ready(function () { window.changedTests = new Set(); function endsWith(string, suffix) { return string.indexOf(suffix, string.length - suffix.length) !== -1; } const inputFileDiv = $("div.input-file"); const inputFile = inputFileDiv.text(); const outputFileDiv = $("div.output-file"); const outputFile = outputFileDiv.text(); if (!endsWith(inputFile, "стандартный ввод") && !endsWith(inputFile, "standard input")) { inputFileDiv.attr("style", "font-weight: bold"); } if (!endsWith(outputFile, "стандартный вывод") && !endsWith(outputFile, "standard output")) { outputFileDiv.attr("style", "font-weight: bold"); } const titleDiv = $("div.header div.title"); String.prototype.replaceAll = function (search, replace) { return this.split(search).join(replace); }; $(".sample-test .title").each(function () { const preId = ("id" + Math.random()).replaceAll(".", "0"); const cpyId = ("id" + Math.random()).replaceAll(".", "0"); $(this).parent().find("pre").attr("id", preId); const $copy = $("<div title='Скопировать' data-clipboard-target='#" + preId + "' id='" + cpyId + "' class='input-output-copier'>Скопировать</div>"); $(this).append($copy); const clipboard = new Clipboard('#' + cpyId, { text: function (trigger) { const pre = document.querySelector('#' + preId); const lines = pre.querySelectorAll(".test-example-line"); return Codeforces.filterClipboardText(pre.innerText, lines.length); } }); const isInput = $(this).parent().hasClass("input"); clipboard.on('success', function (e) { if (isInput) { Codeforces.showMessage("Входные данные были скопированы в буфер обмена"); } else { Codeforces.showMessage("Выходные данные были скопированы в буфер обмена"); } e.clearSelection(); }); }); $(".test-form-item input").change(function () { addPendingSubmissionMessage($($(this).closest("form")), "Вы изменили ответ, не забудьте его отправить, если вы хотите сохранить изменения"); const index = $(this).closest(".problemindexholder").attr("problemindex"); let test = ""; $(this).closest("form input").each(function () { const test_ = $(this).attr("name"); if (test_ && test_.substring(0, 4) === "test") { test = test_; } }); if (index.length > 0 && test.length > 0) { const indexTest = index + "::" + test; window.changedTests.add(indexTest); } }); $(window).on('beforeunload', function () { if (window.changedTests.size > 0) { return 'Dialog text here'; } }); autosize($('.test-explanation textarea')); $(".test-example-line").hover(function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { let top = 1E20; let left = 1E20; let problem = $(this).closest(".problemindexholder"); $(this).closest(".input").find("." + clazz).css("background-color", "#FFFDE7").each(function() { top = Math.min(top, $(this).offset().top); left = Math.min(left, $(this).offset().left); }); let testCaseMarker = problem.find(".testCaseMarker_" + end); if (testCaseMarker.length === 0) { const html = "<div class=\"testCaseMarker testCaseMarker_" + end + " notice\"></div>"; problem.append($(html)); testCaseMarker = problem.find(".testCaseMarker_" + end); } if (testCaseMarker) { testCaseMarker.show() .offset({top, left: left - 20}) .text(end); } } } }); }, function() { $(this).attr("class").split(" ").forEach((clazz) => { if (clazz.substr(0, "test-example-line-".length) === "test-example-line-") { let end = clazz.substr("test-example-line-".length); if (end !== "even" && end !== "odd" && end !== "0") { $("." + clazz).css("background-color", ""); $(this).closest(".problemindexholder").find(".testCaseMarker_" + end).hide(); } } }); }); }); </script> </div> </div> <br style="clear: both;"/> <div id="footer"> <div><a href="https://codeforces.com/">Codeforces</a> (c) Copyright 2010-2023 Михаил Мирзаянов</div> <div>Соревнования по программированию 2.0</div> <div>Время на сервере: <span class="format-timewithseconds" data-locale="ru">07.10.2023 15:37:45</span> (h1).</div> <div>Десктопная версия, переключиться на <a rel="nofollow" class="switchToMobile" href="?mobile=true">мобильную</a>.</div> <div class="smaller"><a href="/privacy">Privacy Policy</a></div> <div style="margin-top: 25px;"> При поддержке </div> <div style="margin-top: 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/ru/"><img style="width: 130px;" src="//codeforces.org/s/81027/images/itmo_small_ru-logo.png" alt="ИТМО" title="ИТМО"/></a> </div> </div> <script type="text/javascript"> $(function() { $(".switchToMobile").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "true")); return false; }); $(".switchToDesktop").click(function() { Codeforces.redirect(Codeforces.updateUrlParameter(document.location.href, "mobile", "false")); return false; }); }); </script> <script type="text/javascript"> $(document).ready(function () { if ($(window).width() < 1600) { $('.button-up').css('width', '30px').css('line-height', '30px').css('font-size', '20px'); } if ($(window).width() >= 1200) { $ (window).scroll (function () { if ($ (this).scrollTop () > 100) { $ ('.button-up').fadeIn(); } else { $ ('.button-up').fadeOut(); } }); $('.button-up').click(function () { $('body,html').animate({ scrollTop: 0 }, 500); return false; }); $('.button-up').hover(function () { $(this).animate({ 'opacity':'1' }).css({'background-color':'#e7ebf0','color':'#6a86a4'}); }, function () { $(this).animate({ 'opacity':'0.7' }).css({'background':'none','color':'#d3dbe4'});; }); } Codeforces.focusOnError(); }); </script> <div class="userListsFacebox" style="display:none;"> <div style="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/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>Название</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <script type="text/javascript"> $(document).ready(function () { // Create new ':containsIgnoreCase' selector for search jQuery.expr[':'].containsIgnoreCase = function(a, i, m) { return jQuery(a).text().toUpperCase() .indexOf(m[3].toUpperCase()) >= 0; }; if (window.updateDatatableFilter == undefined) { window.updateDatatableFilter = function(i) { var parent = $(i).parent().parent().parent().parent(); $("tr.no-items", parent).remove(); $("tr", parent).hide().removeClass('visible'); var text = $(i).val(); if (text) { $("tr" + ":containsIgnoreCase('" + text + "')", parent).show().addClass('visible'); } else { parent.find(".rowCount").text(""); $("tr", parent).show().addClass('visible'); } var found = false; var visibleRowCount = 0; $("tr", parent).each(function () { if (!found) { if ($(this).find("th").size() > 0) { $(this).show().addClass('visible'); found = true; } } if ($(this).hasClass('visible')) { visibleRowCount++; } }); if (text) { parent.find(".rowCount").text("Совпадений: " + (visibleRowCount - (found ? 1 : 0))); } if (visibleRowCount == (found ? 1 : 0)) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo($(parent).find('table')); } $(parent).find("tr td").removeClass("dark"); $(parent).find("tr.visible:odd td").addClass("dark"); } $(".datatable .closed").click(function () { var parent = $(this).parent(); $(this).hide(); $(".filter", parent).fadeIn(function () { $("input", parent).val("").focus().css("border", "1px solid #aaa"); }); }); $(".datatable .opened").click(function () { var parent = $(this).parent().parent(); $(".filter", parent).fadeOut(function () { $(".closed", parent).show(); $("input", parent).val("").each(function () { window.updateDatatableFilter(this); }); }); }); $(".datatable .filter input").keyup(function(e) { window.updateDatatableFilter(this); e.preventDefault(); e.stopPropagation(); }); $(".datatable table").each(function () { var found = false; $("tr", this).each(function () { if (!found && $(this).find("th").size() == 0) { found = true; } }); if (!found) { $("<tr class='no-items visible'><td style=\"text-align:left;\"colspan=\"32\">Нет данных<\/td><\/tr>").appendTo(this); } }); // Applies styles to datatables. $(".datatable").each(function () { $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); $(".datatable table.tablesorter").each(function () { $(this).bind("sortEnd", function () { $(".datatable").each(function () { $(this).find("th, td") .removeClass("top").removeClass("bottom") .removeClass("left").removeClass("right") .removeClass("dark"); $(this).find("tr:first th").addClass("top"); $(this).find("tr:last td").addClass("bottom"); $(this).find("tr:odd td").addClass("dark"); $(this).find("tr td:first-child, tr th:first-child").addClass("left"); $(this).find("tr td:last-child, tr th:last-child").addClass("right"); }); }); }); } }); </script> </div> </div> <script type="application/javascript"> $(function() { $(".userListMarker").click(function() { $.post("/data/lists", {action: "findTouched"}, function(json) { Codeforces.facebox(".userListsFacebox"); var tbody = $("#facebox tbody"); tbody.empty(); for (var i in json) { tbody.append( $("<tr></tr>").append( $("<td></td>").attr("data-readKey", json[i].readKey).text(json[i].name) ) ); } Codeforces.updateDatatables(); tbody.find("td").css("cursor", "pointer").click(function() { document.location = Codeforces.updateUrlParameter(document.location.href, "list", $(this).attr("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:'81263281a9c575bb',t:'MTY5NjY4MjI2NS45NTUwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0418\u043d\u0442\u0435\u0433\u0440\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435, \u0434\u0438\u0444\u0444\u0443\u0440\u044b \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u043c\u0430\u0442\u0435\u043c\u0430\u0442\u0438\u043a\u0430", "*1200"]
1221D
1221
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$$$ вертикальных досок. Ширина каждой доски равна $$$1$$$. Высота $$$i$$$-й доски равна $$$a_i$$$. Вы считаете забор <span class="tex-font-style-it">великим</span>, если все соседние доски имеют разную высоту. Формально, забор великий, если для любого индекса от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \neq a_i$$$.</p><p>К сожалению, ваш забор может быть не великим. Но вы можете это исправить! Вы можете увеличить длину $$$i$$$-й доски на $$$1$$$, но за это вам придется заплатить $$$b_i$$$ рублей. Длину каждой доски можно увеличивать любое количество раз (в том числе, можно не увеличивать её длину совсем).</p><p>Посчитайте минимальное количество рублей, которое вам нужно потратить, для того чтобы сделать забор великим снова!</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество досок в заборе.</p><p>Следующие $$$n$$$ строк каждого запроса содержат описание досок.$$$i$$$-я строка содержит два числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$) — длину $$$i$$$-й доски и цену за увеличение её длины на $$$1$$$, соответственно.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p><p><span class="tex-font-style-bf">Так же гарантируется, что ответ не превосходит $$$10^{18}$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите число в отдельной строке — минимальное количество рублей, которое вам нужно потратить, для того чтобы сделать забор великим.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 4 2 1 3 5 3 2 3 2 10 2 6 4 1 7 3 3 2 6 1000000000 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 9 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вам нужно увеличить длину второй доски на $$$2$$$. Тогда всего вы потратите $$$2 \cdot b_2 = 2$$$ рублей.</p><p>Во втором запросе вам нужно увеличить длину первой доски на $$$1$$$ и длину третьей доски на $$$1$$$. Таким образом, вы потратите $$$1 \cdot b_1 + 1 \cdot b_3 = 9$$$ рублей.</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="3e5bab48fb7f6c3c9672e923f2c3bc59"/> <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="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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='3e5bab48fb7f6c3c9672e923f2c3bc59'>&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%2F1221%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='3e5bab48fb7f6c3c9672e923f2c3bc59'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='3e5bab48fb7f6c3c9672e923f2c3bc59'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='3e5bab48fb7f6c3c9672e923f2c3bc59'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415610"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='3e5bab48fb7f6c3c9672e923f2c3bc59'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415610"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" 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/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" 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/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_5f8d32d3b9ef94d3c4febadf42bedbc5a358b7ed"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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$$$ вертикальных досок. Ширина каждой доски равна $$$1$$$. Высота $$$i$$$-й доски равна $$$a_i$$$. Вы считаете забор <span class="tex-font-style-it">великим</span>, если все соседние доски имеют разную высоту. Формально, забор великий, если для любого индекса от $$$2$$$ до $$$n$$$, выполняется условие $$$a_{i-1} \neq a_i$$$.</p><p>К сожалению, ваш забор может быть не великим. Но вы можете это исправить! Вы можете увеличить длину $$$i$$$-й доски на $$$1$$$, но за это вам придется заплатить $$$b_i$$$ рублей. Длину каждой доски можно увеличивать любое количество раз (в том числе, можно не увеличивать её длину совсем).</p><p>Посчитайте минимальное количество рублей, которое вам нужно потратить, для того чтобы сделать забор великим снова!</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит число $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — количество досок в заборе.</p><p>Следующие $$$n$$$ строк каждого запроса содержат описание досок.$$$i$$$-я строка содержит два числа $$$a_i$$$ и $$$b_i$$$ ($$$1 \le a_i, b_i \le 10^9$$$) — длину $$$i$$$-й доски и цену за увеличение её длины на $$$1$$$, соответственно.</p><p>Гарантируется, что сумма $$$n$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p><p><span class="tex-font-style-bf">Так же гарантируется, что ответ не превосходит $$$10^{18}$$$.</span></p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите число в отдельной строке — минимальное количество рублей, которое вам нужно потратить, для того чтобы сделать забор великим.</p></div><div class="sample-tests"><div class="section-title">Пример</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 3 3 2 4 2 1 3 5 3 2 3 2 10 2 6 4 1 7 3 3 2 6 1000000000 2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 2 9 0 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе вам нужно увеличить длину второй доски на $$$2$$$. Тогда всего вы потратите $$$2 \cdot b_2 = 2$$$ рублей.</p><p>Во втором запросе вам нужно увеличить длину первой доски на $$$1$$$ и длину третьей доски на $$$1$$$. Таким образом, вы потратите $$$1 \cdot b_1 + 1 \cdot b_3 = 9$$$ рублей.</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 10:45: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:'812486753e629da4',t:'MTY5NjY2NDczMy4xMzIwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "*1800"]
1221E
1221
E
ru
E. Игра со строкой
<div class="problem-statement"><div class="header"><div class="title">E. Игра со строкой</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3 секунды</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. Изначально у них есть строка $$$s_1, s_2, \dots, s_n$$$, состоящая только из символов <span class="tex-font-style-tt">.</span> и <span class="tex-font-style-tt">X</span>. Игроки ходят по очереди, и Алиса ходит первой. В течении хода игрок должен выбрать непрерывную подстроку, состоящую только из символов <span class="tex-font-style-tt">.</span>, и заменить каждый символ в ней на <span class="tex-font-style-tt">X</span>. Алиса выбирает подстроки длины ровно $$$a$$$, а Боб выбирает подстроки длины ровно $$$b$$$. Гарантируется, что $$$a &gt; b$$$.</p><p>Например, если $$$s =$$$ <span class="tex-font-style-tt">...X..</span> и $$$a = 3$$$, $$$b = 2$$$, то после хода Алисы строка может превратиться только в <span class="tex-font-style-tt">XXXX..</span>. Если $$$s =$$$ <span class="tex-font-style-tt">...X..</span>, и сейчас ход Боба, то после него строка может превратиться в <span class="tex-font-style-tt">XX.X..</span>, <span class="tex-font-style-tt">.XXX..</span> или <span class="tex-font-style-tt">...XXX</span>.</p><p>Игрок, который не может сделать ход, считается проигравшим. Вам нужно определить, кто выиграет в этой игре если оба игрока играют оптимально.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два числа $$$a$$$ и $$$b$$$ ($$$1 \le b &lt; a \le 3 \cdot 10^5$$$).</p><p>Вторая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 3 \cdot 10^5$$$), состоящую только из символов <span class="tex-font-style-tt">.</span> и <span class="tex-font-style-tt">X</span>.</p><p>Гарантируется, что сумма $$$|s|$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите <span class="tex-font-style-tt">YES</span>, если Алиса может выиграть, и <span class="tex-font-style-tt">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> 3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Алиса может выбрать подстроку $$$s_3 \dots s_5$$$. После этого $$$s$$$ превратится в <span class="tex-font-style-tt">XXXXX...XX...X</span>. Теперь, независимо от хода Боба, у Алисы будет возможность сделать второй ход, а вот Боб второй ход сделать не сможет.</p><p>Во втором запросе Алиса не может выиграть, так как не может сделать даже первый ход.</p><p>В третьем запросе Алиса может выбрать подстроку $$$s_2 \dots s_6$$$. После этого $$$s$$$ превратится в <span class="tex-font-style-tt">.XXXXX.X..X</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="c9c73eee2501d3791acb0fd184154a9a"/> <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="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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='c9c73eee2501d3791acb0fd184154a9a'>&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%2F1221%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='c9c73eee2501d3791acb0fd184154a9a'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='c9c73eee2501d3791acb0fd184154a9a'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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='c9c73eee2501d3791acb0fd184154a9a'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415611"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='c9c73eee2501d3791acb0fd184154a9a'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415611"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" 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/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" 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/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f55c5fd1816741fdf052309fb14ce55610853db3"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Алиса и Боб играют в игру. Изначально у них есть строка $$$s_1, s_2, \dots, s_n$$$, состоящая только из символов <span class="tex-font-style-tt">.</span> и <span class="tex-font-style-tt">X</span>. Игроки ходят по очереди, и Алиса ходит первой. В течении хода игрок должен выбрать непрерывную подстроку, состоящую только из символов <span class="tex-font-style-tt">.</span>, и заменить каждый символ в ней на <span class="tex-font-style-tt">X</span>. Алиса выбирает подстроки длины ровно $$$a$$$, а Боб выбирает подстроки длины ровно $$$b$$$. Гарантируется, что $$$a &gt; b$$$.</p><p>Например, если $$$s =$$$ <span class="tex-font-style-tt">...X..</span> и $$$a = 3$$$, $$$b = 2$$$, то после хода Алисы строка может превратиться только в <span class="tex-font-style-tt">XXXX..</span>. Если $$$s =$$$ <span class="tex-font-style-tt">...X..</span>, и сейчас ход Боба, то после него строка может превратиться в <span class="tex-font-style-tt">XX.X..</span>, <span class="tex-font-style-tt">.XXX..</span> или <span class="tex-font-style-tt">...XXX</span>.</p><p>Игрок, который не может сделать ход, считается проигравшим. Вам нужно определить, кто выиграет в этой игре если оба игрока играют оптимально.</p><p>Вам нужно ответить на $$$q$$$ независимых запросов.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка содержит число $$$q$$$ ($$$1 \le q \le 3 \cdot 10^5$$$) — количество запросов.</p><p>Первая строка каждого запроса содержит два числа $$$a$$$ и $$$b$$$ ($$$1 \le b &lt; a \le 3 \cdot 10^5$$$).</p><p>Вторая строка каждого запроса содержит строку $$$s$$$ ($$$1 \le |s| \le 3 \cdot 10^5$$$), состоящую только из символов <span class="tex-font-style-tt">.</span> и <span class="tex-font-style-tt">X</span>.</p><p>Гарантируется, что сумма $$$|s|$$$ по всем запросам не превосходит $$$3 \cdot 10^5$$$.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>На каждый запрос выведите <span class="tex-font-style-tt">YES</span>, если Алиса может выиграть, и <span class="tex-font-style-tt">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> 3 3 2 XX......XX...X 4 2 X...X.X..X 5 3 .......X..X </pre></div><div class="output"><div class="title">Выходные данные</div><pre> YES NO YES </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>В первом запросе Алиса может выбрать подстроку $$$s_3 \dots s_5$$$. После этого $$$s$$$ превратится в <span class="tex-font-style-tt">XXXXX...XX...X</span>. Теперь, независимо от хода Боба, у Алисы будет возможность сделать второй ход, а вот Боб второй ход сделать не сможет.</p><p>Во втором запросе Алиса не может выиграть, так как не может сделать даже первый ход.</p><p>В третьем запросе Алиса может выбрать подстроку $$$s_2 \dots s_6$$$. После этого $$$s$$$ превратится в <span class="tex-font-style-tt">.XXXXX.X..X</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 10:45: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:'8124867dbf5b5aae',t:'MTY5NjY2NDczNC40ODYwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', 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", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0438\u0433\u0440\u044b", "*2500"]
1221F
1221
F
ru
F. Выбери квадрат
<div class="problem-statement"><div class="header"><div class="title">F. Выбери квадрат</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>6 секунд</div><div class="memory-limit"><div class="property-title">ограничение по памяти на тест</div>256 мегабайт</div><div class="input-file"><div class="property-title">ввод</div>стандартный ввод</div><div class="output-file"><div class="property-title">вывод</div>стандартный вывод</div></div><div><p>Недавно Петя нашел игру «Выбери квадрат». В игре на бесконечном поле расположено $$$n$$$ точек, пронумерованных целыми числами от $$$1$$$ до $$$n$$$. Точка номер $$$i$$$ имеет координаты $$$(x_i, y_i)$$$ и стоимость $$$c_i$$$.</p><p>Необходимо выбрать квадрат, стороны которого параллельны осям координат, левый нижний и правый верхний угол лежат на прямой $$$y = x$$$, и все углы имеют целые координаты.</p><p>Счетом игры является разность суммарной стоимости точек, покрытых выбранным квадратом, и длины стороны квадрата. Сторона квадрата может быть нулевой длины.</p><p>Петя просит вас помочь ему найти максимальный счет в игре, выбрав ровно один квадрат. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество точек на поле.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i, y_i, c_i$$$ ($$$0 \le x_i, y_i \le 10^9, -10^6 \le c_i \le 10^6$$$) — координаты $$$i$$$-й точки и ее стоимость, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите максимальный счет, который можно набрать в игре, выбрав ровно один квадрат.</p><p>Во второй строке выведите четыре целых числа $$$x_1, y_1, x_2, y_2$$$ ($$$0 \le x_1, y_1, x_2, y_2 \le 2 \cdot 10^9, x_1 = y_1, x_2 = y_2, x_1 \le x_2$$$), разделенные пробелами — координаты левого нижнего и правого верхнего углов квадрата, которые необходимо выбрать Пете, чтобы набрать максимальный счет.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 0 0 2 1 0 -5 1 1 3 2 3 4 1 4 -4 3 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 1 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 3 0 3 3 -3 0 2 -1 3 1 3 0 0 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Игровое поле, соответствующее первому тестовому примеру: <img class="tex-graphics" src="https://espresso.codeforces.com/95e8646dab79eca87a0eccb35cdf644a1231e3bc.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="b7e57cd4f19f560eabe433891bb5d1f1"/> <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="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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='b7e57cd4f19f560eabe433891bb5d1f1'>&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%2F1221%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='b7e57cd4f19f560eabe433891bb5d1f1'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='b7e57cd4f19f560eabe433891bb5d1f1'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Сложность"> *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='b7e57cd4f19f560eabe433891bb5d1f1'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415612"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='b7e57cd4f19f560eabe433891bb5d1f1'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415612"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" 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/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" 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/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_00eb77c9b2330a5976fe60abeaecbfa17a201b73"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>256 мегабайт</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$$$ имеет координаты $$$(x_i, y_i)$$$ и стоимость $$$c_i$$$.</p><p>Необходимо выбрать квадрат, стороны которого параллельны осям координат, левый нижний и правый верхний угол лежат на прямой $$$y = x$$$, и все углы имеют целые координаты.</p><p>Счетом игры является разность суммарной стоимости точек, покрытых выбранным квадратом, и длины стороны квадрата. Сторона квадрата может быть нулевой длины.</p><p>Петя просит вас помочь ему найти максимальный счет в игре, выбрав ровно один квадрат. </p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>Первая строка входных данных содержит одно целое число $$$n$$$ ($$$1 \le n \le 5 \cdot 10^5$$$) — количество точек на поле.</p><p>Каждая из следующих $$$n$$$ строк содержит три целых числа $$$x_i, y_i, c_i$$$ ($$$0 \le x_i, y_i \le 10^9, -10^6 \le c_i \le 10^6$$$) — координаты $$$i$$$-й точки и ее стоимость, соответственно.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>В первой строке выведите максимальный счет, который можно набрать в игре, выбрав ровно один квадрат.</p><p>Во второй строке выведите четыре целых числа $$$x_1, y_1, x_2, y_2$$$ ($$$0 \le x_1, y_1, x_2, y_2 \le 2 \cdot 10^9, x_1 = y_1, x_2 = y_2, x_1 \le x_2$$$), разделенные пробелами — координаты левого нижнего и правого верхнего углов квадрата, которые необходимо выбрать Пете, чтобы набрать максимальный счет.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 0 0 2 1 0 -5 1 1 3 2 3 4 1 4 -4 3 1 -1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 1 1 3 3 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 5 3 3 0 3 3 -3 0 2 -1 3 1 3 0 0 -2 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 0 1 1 1 1 </pre></div></div></div><div class="note"><div class="section-title">Примечание</div><p>Игровое поле, соответствующее первому тестовому примеру: <img class="tex-graphics" src="https://espresso.codeforces.com/95e8646dab79eca87a0eccb35cdf644a1231e3bc.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=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 10:45: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:'812486862cfe2de5',t:'MTY5NjY2NDczNS44MTQwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["\u0411\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0421\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438, \u0443\u043f\u043e\u0440\u044f\u0434\u043e\u0447\u0435\u043d\u0438\u044f", "\u041a\u0443\u0447\u0438, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043e\u0442\u0440\u0435\u0437\u043a\u043e\u0432, \u0434\u0435\u0440\u0435\u0432\u044c\u044f \u043f\u043e\u0438\u0441\u043a\u0430 \u0438 \u0434\u0440.", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["\u0431\u0438\u043d\u0430\u0440\u043d\u044b\u0439 \u043f\u043e\u0438\u0441\u043a", "\u0441\u043e\u0440\u0442\u0438\u0440\u043e\u0432\u043a\u0438", "\u0441\u0442\u0440\u0443\u043a\u0442\u0443\u0440\u044b \u0434\u0430\u043d\u043d\u044b\u0445", "*2400"]
1221G
1221
G
ru
G. Граф и числа
<div class="problem-statement"><div class="header"><div class="title">G. Граф и числа</div><div class="time-limit"><div class="property-title">ограничение по времени на тест</div>3.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$$$ ребер. Вы должны написать число на каждой вершине графа, каждое число должно быть равно $$$0$$$ или $$$1$$$. После этого на каждом ребре будет записана сумма чисел на двух вершинах, инцидентных этому ребру.</p><p>Вы должны выбрать числа таким образом, чтобы было хотя бы одно ребро с числом $$$0$$$, хотя бы одно ребро с числом $$$1$$$ и хотя бы одно ребро с числом $$$2$$$. Сколько способов так расставить числа? Два способа различны, если существует хотя бы одна вершина, на которой в разных способах записаны разные числа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 40$$$, $$$0 \le m \le \frac{n(n - 1)}{2}$$$) — количество вершин и ребер, соответственно.</p><p>Затем следуют $$$m$$$ строк, в каждой из которых записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — вершины, соединяемые $$$i$$$-м ребром. Гарантируется, что между каждой парой вершин существует не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество способов так записать числа на вершинах, что есть хотя бы одно ребро с числом $$$0$$$, хотя бы одно ребро с числом $$$1$$$ и хотя бы одно ребро с числом $$$2$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 1 2 2 3 3 4 4 5 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 35 29 1 2 2 3 3 1 4 1 4 2 3 4 7 8 8 9 9 10 10 7 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 34201047040 </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="5d7e7fe764d7a16fdeab31dfae03d2e0"/> <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="91f6b79ed0dcae895cc22a2d93d66e427af6a3e5"/> <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='5d7e7fe764d7a16fdeab31dfae03d2e0'>&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%2F1221%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='5d7e7fe764d7a16fdeab31dfae03d2e0'/> <input class="search" name="query" data-isPlaceholder="true" value=""/> </form> <br style="clear: both;"/> </div> </div> <script type="text/javascript"> $(document).ready(function () { $("input.search").focus(function () { if ($(this).attr("data-isPlaceholder") === "true") { $(this).val(""); $(this).removeAttr("data-isPlaceholder"); } }); }); </script> <br style="height: 3em; clear: both;"/> <div style="position: relative;"> <div id="sidebar"> <div class="roundbox sidebox borderTopRound " style=""> <table class="rtable "> <tbody> <tr> <th class="left" style="width:100%;"><a style="color: black" href="/contest/1221">Educational Codeforces Round 73 (рейтинговый для Див. 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='5d7e7fe764d7a16fdeab31dfae03d2e0'/> <input type="hidden" name="action" value="registerForPractice"/> <input type="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/1221/virtual" method="get"> <input type="submit" name="submit" value="Начать виртуальное участие" style="padding:0 0.5em;"> </form> </div> </div> <script> $(function () { $(".ContestVirtualFrame .sidebar-caption-icon").click(function() { $(this).toggleClass("la-angle-down la-angle-right"); const $target = $(this).parent().next(); $target.toggle(); const dataPageUrl = $target.attr("data-page-url"); const collapsed = $(this).hasClass("la-angle-right"); const params = { action: "setCollapsed", sidebarFrameSimpleClassName: "ContestVirtualFrame", collapsed }; $.each($target[0].attributes, function(i, a) { const name = a.name; if (name.startsWith("data-extra-key-")) { const key = a.value; const keyIndex = parseInt(name.substring("data-extra-key-".length)); const value = $target.attr("data-extra-value-" + keyIndex); params[key] = value; } }); $.post(dataPageUrl, 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="Meet-in-the-middle"> meet-in-the-middle </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Битовые маски"> битмаски </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Динамическое программирование"> дп </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Комбинаторика"> комбинаторика </span> </div> <div class="roundbox borderTopRound borderBottomRound" style="margin:2px; padding:0 3px 2px 3px; background-color:#f0f0f0;float:left;"> <span class="tag-box" style="font-size:1.2rem;" title="Перебор"> перебор </span> </div> <div class="roundbox borderTopRound 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='5d7e7fe764d7a16fdeab31dfae03d2e0'/> <input name="action" type="hidden" value="addTag"/> <input name="problemId" type="hidden" value="415613"/> <input name="tagName" type="hidden" value=""/> </form> <form id="removeTagForm" action="/data/problemTags" method="post" style="display:none;"><input type='hidden' name='csrf_token' value='5d7e7fe764d7a16fdeab31dfae03d2e0'/> <input name="action" type="hidden" value="removeTag"/> <input name="problemId" type="hidden" value="415613"/> <input name="tagName" type="hidden" value=""/> </form> <script type="text/javascript"> $(".tag-box img").click(function () { var tagName = $(this).attr("value"); Codeforces.confirm("Вы уверены, что хотите удалить этот тег?", function () { $("#removeTagForm input[name=tagName]").val(tagName); $("#removeTagForm").submit(); }, function () { }, "Да", "Нет"); }); $("#addTagLink").click(function () { $(this).hide(); $("#addTagLabel").show(); return false; }); $("#addTagSelect").change(function () { var tagName = $(this).val(); if (tagName === "") { $("#addTagLabel").hide(); $("#addTagLink").show(); } else { $("#addTagForm input[name=tagName]").val(tagName); $("#addTagForm").submit(); } }); </script> <style type="text/css"> #new-resource-form tr td { padding-top: 0.5em; } #new-resource-form input:not([type="submit"]) { font-size: 0.8em; } #new-resource-form select { font-size: 0.8em; } .new-resource-error { font-size: 0.8em; } .resource-locale { color: #666; font-family: Consolas, "Andale Mono WT", "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", "DejaVu Sans Mono", "Bitstream Vera Sans 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/69868" title="Educational Codeforces Round 73 [рейтинговый для Div. 2]" target="_blank">Анонс</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9686:9687" 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/69925" title="Разбор Educational Codeforces Round 73" target="_blank">Разбор задач</a> </span> <span style="float: right;"> <img class="delete-resource-link" resourceIds="9385:9386" 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/1221">Задачи</a></li> <li><a href="/contest/1221/submit">Отослать</a></li> <li><a href="/contest/1221/my">Мои посылки</a></li> <li><a href="/contest/1221/status">Статус</a></li> <li><a href="/contest/1221/hacks">Взломы</a></li> <li><a href="/contest/1221/standings">Положение</a></li> <li><a href="/contest/1221/customtest">Запуск</a></li> </ul> </div> <style> #facebox .content:has(.diff-popup) { width: 90vw; max-width: 120rem !important; } .testCaseMarker { position: absolute; font-weight: bold; font-size: 1rem; } .diff-popup { width: 90vw; max-width: 120rem !important; display: none; overflow: auto; } .input-output-copier { font-size: 1.2rem; float: right; color: #888 !important; cursor: pointer; border: 1px solid rgb(185, 185, 185); padding: 3px; margin: 1px; line-height: 1.1rem; text-transform: none; } .input-output-copier:hover { background-color: #def; } .test-explanation textarea { width: 100%; height: 1.5em; } .pending-submission-message { color: darkorange !important; } </style> <script> const OPENING_SPACE = String.fromCharCode(1001); const CLOSING_SPACE = String.fromCharCode(1002); const nodeToText = function (node, pre) { let result = []; if (node.tagName === "SCRIPT" || node.tagName === "math" || (node.classList && node.classList.contains("input-output-copier"))) return []; if (node.tagName === "NOBR") { result.push(OPENING_SPACE); } if (node.nodeType === Node.TEXT_NODE) { let s = node.textContent; if (!pre) { s = s.replace(/\s+/g, " "); } if (s.length > 0) { result.push(s); } } if (pre && node.tagName === "BR") { result.push("\n"); } node.childNodes.forEach(function (child) { result.push(nodeToText(child, node.tagName === "PRE").join("")); }); if (node.tagName === "DIV" || node.tagName === "P" || node.tagName === "PRE" || node.tagName === "UL" || node.tagName === "LI" ) { result.push("\n"); } if (node.tagName === "NOBR") { result.push(CLOSING_SPACE); } return result; } const isSpecial = function (c) { return c === ',' || c === '.' || c === ';' || c === ')' || c === ' '; } const convertStatementToText = function(statmentNode) { const text = nodeToText(statmentNode, false).join("").replace(/ +/g, " ").replace(/\n\n+/g, "\n\n"); let result = []; for (let i = 0; i < text.length; i++) { const c = text.charAt(i); if (c === OPENING_SPACE) { if (!((i > 0 && text.charAt(i - 1) === '(') || (result.length > 0 && result[result.length - 1] === ' '))) { result.push('+'); } } else if (c === CLOSING_SPACE) { if (!(i + 1 < text.length && isSpecial(text.charAt(i + 1)))) { result.push('-'); } } else { 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_f58481c3547413db442657b5c7869af2a1292281"> <div style="display: none; margin:1em 0;text-align: center; position: relative;" class="alert alert-info diff-notifier"> <div>Условие задачи было недавно изменено. <a class="view-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>3.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$$$ ребер. Вы должны написать число на каждой вершине графа, каждое число должно быть равно $$$0$$$ или $$$1$$$. После этого на каждом ребре будет записана сумма чисел на двух вершинах, инцидентных этому ребру.</p><p>Вы должны выбрать числа таким образом, чтобы было хотя бы одно ребро с числом $$$0$$$, хотя бы одно ребро с числом $$$1$$$ и хотя бы одно ребро с числом $$$2$$$. Сколько способов так расставить числа? Два способа различны, если существует хотя бы одна вершина, на которой в разных способах записаны разные числа.</p></div><div class="input-specification"><div class="section-title">Входные данные</div><p>В первой строке заданы два целых числа $$$n$$$ и $$$m$$$ ($$$1 \le n \le 40$$$, $$$0 \le m \le \frac{n(n - 1)}{2}$$$) — количество вершин и ребер, соответственно.</p><p>Затем следуют $$$m$$$ строк, в каждой из которых записаны два целых числа $$$x_i$$$ и $$$y_i$$$ ($$$1 \le x_i, y_i \le n$$$, $$$x_i \ne y_i$$$) — вершины, соединяемые $$$i$$$-м ребром. Гарантируется, что между каждой парой вершин существует не более одного ребра.</p></div><div class="output-specification"><div class="section-title">Выходные данные</div><p>Выведите одно целое число — количество способов так записать числа на вершинах, что есть хотя бы одно ребро с числом $$$0$$$, хотя бы одно ребро с числом $$$1$$$ и хотя бы одно ребро с числом $$$2$$$.</p></div><div class="sample-tests"><div class="section-title">Примеры</div><div class="sample-test"><div class="input"><div class="title">Входные данные</div><pre> 6 5 1 2 2 3 3 4 4 5 5 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 20 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 4 4 1 2 2 3 3 4 4 1 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 4 </pre></div><div class="input"><div class="title">Входные данные</div><pre> 35 29 1 2 2 3 3 1 4 1 4 2 3 4 7 8 8 9 9 10 10 7 11 12 12 13 13 14 14 15 15 16 16 17 17 18 18 19 19 20 20 21 21 22 22 23 23 24 24 25 25 26 26 27 27 28 28 29 29 30 </pre></div><div class="output"><div class="title">Выходные данные</div><pre> 34201047040 </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 10:45: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:'8124868e7dc67b7f',t:'MTY5NjY2NDczNy4xNTEwMDA='};_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/scripts/jsd/main.js',document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();</script></body> </html>
["Meet-in-the-middle", "\u0411\u0438\u0442\u043e\u0432\u044b\u0435 \u043c\u0430\u0441\u043a\u0438", "\u0414\u0438\u043d\u0430\u043c\u0438\u0447\u0435\u0441\u043a\u043e\u0435 \u043f\u0440\u043e\u0433\u0440\u0430\u043c\u043c\u0438\u0440\u043e\u0432\u0430\u043d\u0438\u0435", "\u041a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u041f\u0435\u0440\u0435\u0431\u043e\u0440", "\u0421\u043b\u043e\u0436\u043d\u043e\u0441\u0442\u044c"]
["meet-in-the-middle", "\u0431\u0438\u0442\u043c\u0430\u0441\u043a\u0438", "\u0434\u043f", "\u043a\u043e\u043c\u0431\u0438\u043d\u0430\u0442\u043e\u0440\u0438\u043a\u0430", "\u043f\u0435\u0440\u0435\u0431\u043e\u0440", "*2900"]